1
//! `transaction` subcommands, built from the compiled-in form descriptors.
2

            
3
use clap::builder::PossibleValuesParser;
4
use clap::error::ErrorKind;
5
use clap::{Arg, ArgAction, ArgMatches, Command, Error, FromArgMatches, Subcommand, value_parser};
6
use cli_core::CommandError;
7
use cli_core::transaction as ops;
8
use forms::{Action, Field, Form, FormValues, Kind, PAGING_KEYS, Row};
9
use rows_args::{
10
    clear_arg, clear_id, has_clear, is_carried, is_free_rows, is_nested_tags, row_long,
11
};
12
use rpc::Session;
13
use split_tag::{SPLIT_TAG_HELP, parse_split_tag};
14
use sqlx::types::Uuid;
15
use std::io::{BufRead, IsTerminal};
16

            
17
mod rows_args;
18
mod split_tag;
19

            
20
const ROW_HELP: &str = "A split as key=value pairs joined by commas, e.g. \
21
    from=Cash,to=Food,from-commodity=USD,value=5. Repeat for more splits. \
22
    Error addresses count rows from 0 (splits.0 is the first --row). Write \\, for a comma and \\\\ for a backslash inside a value. \
23
    An omitted to-commodity means from-commodity. \
24
    On edit, key=rN selects a loaded split and changes only the given cells; a row without key is appended.";
25

            
26
#[derive(Debug)]
27
pub enum TransactionCmd {
28
    Create(FormValues),
29
    CreateFromTemplate {
30
        template: Uuid,
31
        overrides: FormValues,
32
    },
33
    List(FormValues),
34
    Show {
35
        id: Uuid,
36
    },
37
    Edit {
38
        id: Uuid,
39
        overrides: FormValues,
40
        drop_rows: Vec<String>,
41
    },
42
    Delete {
43
        id: Uuid,
44
        yes: bool,
45
    },
46
}
47

            
48
impl Subcommand for TransactionCmd {
49
135
    fn augment_subcommands(cmd: Command) -> Command {
50
135
        cmd.subcommand_required(true)
51
135
            .arg_required_else_help(true)
52
135
            .subcommand(create_command())
53
135
            .subcommand(form_command(
54
135
                "list",
55
135
                "List transactions",
56
135
                &forms::TRANSACTION_QUERY,
57
135
            ))
58
135
            .subcommand(
59
135
                Command::new("show")
60
135
                    .about("Show a transaction")
61
135
                    .arg(id_arg()),
62
135
            )
63
135
            .subcommand(edit_command())
64
135
            .subcommand(
65
135
                Command::new("delete")
66
135
                    .about("Delete a transaction")
67
135
                    .arg(id_arg())
68
135
                    .arg(
69
135
                        Arg::new("yes")
70
135
                            .long("yes")
71
135
                            .action(ArgAction::SetTrue)
72
135
                            .help("Delete without asking; required when stdin is not a terminal"),
73
135
                    ),
74
135
            )
75
135
    }
76

            
77
    fn augment_subcommands_for_update(cmd: Command) -> Command {
78
        Self::augment_subcommands(cmd)
79
    }
80

            
81
    fn has_subcommand(name: &str) -> bool {
82
        matches!(name, "create" | "list" | "show" | "edit" | "delete")
83
    }
84
}
85

            
86
impl FromArgMatches for TransactionCmd {
87
29
    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
88
29
        match matches.subcommand() {
89
15
            Some(("create", sub)) => create_of(sub),
90
3
            Some(("list", sub)) => Ok(Self::List(values_of(&forms::TRANSACTION_QUERY, sub))),
91
1
            Some(("show", sub)) => Ok(TransactionCmd::Show { id: id_of(sub)? }),
92
8
            Some(("edit", sub)) => edit_of(sub),
93
2
            Some(("delete", sub)) => delete_of(sub),
94
            Some((name, _)) => Err(Error::raw(
95
                ErrorKind::InvalidSubcommand,
96
                format!("unknown transaction subcommand '{name}'"),
97
            )),
98
            None => Err(Error::raw(
99
                ErrorKind::MissingSubcommand,
100
                "a transaction subcommand is required",
101
            )),
102
        }
103
29
    }
104

            
105
    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
106
        *self = Self::from_arg_matches(matches)?;
107
        Ok(())
108
    }
109
}
110

            
111
747
pub(crate) fn id_arg() -> Arg {
112
747
    Arg::new("id")
113
747
        .required(true)
114
747
        .value_parser(value_parser!(Uuid))
115
747
}
116

            
117
14
pub(crate) fn id_of(sub: &ArgMatches) -> Result<Uuid, Error> {
118
14
    sub.get_one::<Uuid>("id")
119
14
        .copied()
120
        .ok_or_else(|| Error::raw(ErrorKind::MissingRequiredArgument, "the id is required"))
121
14
}
122

            
123
2
fn delete_of(sub: &ArgMatches) -> Result<TransactionCmd, Error> {
124
    Ok(TransactionCmd::Delete {
125
2
        id: id_of(sub)?,
126
2
        yes: sub.get_flag("yes"),
127
    })
128
2
}
129

            
130
135
fn create_command() -> Command {
131
135
    form_command("create", "Create a transaction", &forms::TRANSACTION_CREATE).arg(
132
135
        Arg::new("template")
133
135
            .long("template")
134
135
            .value_name("ID")
135
135
            .value_parser(value_parser!(Uuid))
136
135
            .help("Start from this template's draft; the other options override it"),
137
135
    )
138
135
}
139

            
140
15
fn create_of(sub: &ArgMatches) -> Result<TransactionCmd, Error> {
141
15
    let form = &forms::TRANSACTION_CREATE;
142
15
    match sub.get_one::<Uuid>("template") {
143
        Some(template) => Ok(TransactionCmd::CreateFromTemplate {
144
2
            template: *template,
145
2
            overrides: checked_values(form, sub, false)?,
146
        }),
147
13
        None => checked_values(form, sub, true).map(TransactionCmd::Create),
148
    }
149
15
}
150

            
151
135
fn edit_command() -> Command {
152
135
    form_command(
153
135
        "edit",
154
135
        "Edit a transaction; omitted fields and rows stay as stored",
155
135
        &forms::TRANSACTION_EDIT,
156
135
    )
157
135
    .arg(id_arg())
158
135
    .arg(
159
135
        Arg::new("drop-row")
160
135
            .long("drop-row")
161
135
            .value_name("KEY")
162
135
            .action(ArgAction::Append)
163
135
            .help("Remove the loaded split with this key, e.g. r2"),
164
135
    )
165
135
}
166

            
167
/// The option values, refusing a `--split-tag` that names a missing `--row`.
168
23
fn checked_values(form: &Form, sub: &ArgMatches, date_now: bool) -> Result<FormValues, Error> {
169
23
    let values = values_with(form, sub, date_now);
170
23
    ops::check_split_tags(&values)
171
3
        .map_err(|e| Error::raw(ErrorKind::ValueValidation, e.to_string()))?;
172
20
    Ok(values)
173
23
}
174

            
175
8
fn edit_of(sub: &ArgMatches) -> Result<TransactionCmd, Error> {
176
    Ok(TransactionCmd::Edit {
177
8
        id: id_of(sub)?,
178
8
        overrides: checked_values(&forms::TRANSACTION_EDIT, sub, true)?,
179
7
        drop_rows: sub
180
7
            .get_many::<String>("drop-row")
181
7
            .into_iter()
182
7
            .flatten()
183
7
            .cloned()
184
7
            .collect(),
185
    })
186
8
}
187

            
188
1761
pub(crate) fn form_command(name: &'static str, about: &'static str, form: &Form) -> Command {
189
1761
    form.fields
190
1761
        .iter()
191
7937
        .filter(|field| !matches!(field.kind, Kind::Hidden) && !is_carried(field))
192
6965
        .fold(Command::new(name).about(about), |cmd, field| {
193
6965
            let cmd = cmd.arg(field_arg(form, field));
194
6965
            if has_clear(field) {
195
931
                cmd.arg(clear_arg(field))
196
            } else {
197
6034
                cmd
198
            }
199
6965
        })
200
1761
}
201

            
202
7191
pub(crate) fn field_arg(form: &Form, field: &Field) -> Arg {
203
7191
    let arg = Arg::new(field.key).long(field.key).help(field.label);
204
7191
    match field.kind {
205
        Kind::Rows { fields, .. } => {
206
1217
            let keys = row_keys(fields);
207
1217
            let arg = arg.long(row_long(field)).action(ArgAction::Append);
208
1217
            if is_nested_tags(field) {
209
280
                return arg
210
280
                    .value_name("N:NAME=VALUE[:SIDE]")
211
280
                    .value_parser(parse_split_tag)
212
280
                    .help(SPLIT_TAG_HELP);
213
937
            }
214
937
            let arg = arg
215
937
                .value_name("KEY=VALUE,...")
216
55
                .value_parser(move |spec: &str| parse_row(&keys, spec));
217
937
            if is_free_rows(field) {
218
651
                arg.help(format!(
219
                    "A {} row as key=value pairs joined by commas, e.g. {}. Repeat for more rows; \
220
                     on edit the given rows replace all loaded ones.",
221
651
                    field.label,
222
651
                    row_keys(fields)
223
651
                        .iter()
224
1953
                        .map(|k| format!("{k}=..."))
225
                        .collect::<Vec<_>>()
226
651
                        .join(","),
227
                ))
228
            } else {
229
286
                arg.help(ROW_HELP)
230
            }
231
        }
232
        Kind::Date {
233
            whole_day: true, ..
234
1082
        } => arg
235
1082
            .value_name("DATE")
236
1082
            .help("A day, e.g. 2026-10-27; a range end counts through that day"),
237
286
        Kind::Date { .. } if defaults_to_now(form, field) => arg
238
148
            .value_name("DATE")
239
148
            .help("Date or instant, e.g. 2026-10-27 or 2026-10-27T09:30; defaults to now"),
240
138
        Kind::Date { .. } => arg.value_name("DATE"),
241
550
        Kind::Choice { options, default } => choice_arg(arg, options, default),
242
4056
        _ => match page_default(form, field) {
243
272
            Some(default) => arg.value_name(field.key).default_value(default),
244
3784
            None => arg.value_name(field.key),
245
        },
246
    }
247
7191
}
248

            
249
/// Accepts only the option keys; the server fills in an omitted default.
250
550
fn choice_arg(arg: Arg, options: &[(&'static str, &str)], default: Option<&str>) -> Arg {
251
550
    let listed = options
252
550
        .iter()
253
1910
        .map(|(key, label)| format!("{key} ({label})"))
254
        .collect::<Vec<_>>()
255
550
        .join(", ");
256
550
    let help = match default {
257
546
        Some(default) => format!("One of: {listed}; default: {default}"),
258
4
        None => format!("One of: {listed}"),
259
    };
260
550
    arg.value_name("KEY")
261
550
        .value_parser(PossibleValuesParser::new(
262
1910
            options.iter().map(|(key, _)| *key),
263
        ))
264
550
        .help(help)
265
550
}
266

            
267
/// The query form's paging defaults; also keeps an unfiltered payload non-empty.
268
4056
fn page_default(form: &Form, field: &Field) -> Option<&'static str> {
269
4056
    let [limit_key, _] = PAGING_KEYS;
270
4056
    if form.action != Action::Query || !field.is_paging() {
271
3784
        return None;
272
272
    }
273
272
    Some(if field.key == limit_key { "50" } else { "0" })
274
4056
}
275

            
276
442
fn defaults_to_now(form: &Form, field: &Field) -> bool {
277
442
    form.action == Action::Mutation && matches!(field.kind, Kind::Date { .. })
278
442
}
279

            
280
45
pub(crate) fn values_of(form: &Form, matches: &ArgMatches) -> FormValues {
281
45
    values_with(form, matches, true)
282
45
}
283

            
284
/// The option values; an omitted mutation date is now only when `date_now`.
285
68
fn values_with(form: &Form, matches: &ArgMatches, date_now: bool) -> FormValues {
286
68
    let mut values = FormValues::default();
287
68
    for field in form.fields {
288
325
        match field.kind {
289
26
            Kind::Hidden => {}
290
95
            Kind::Rows { .. } if is_carried(field) => {}
291
            Kind::Rows { .. } => {
292
95
                if has_clear(field) && matches.get_flag(&clear_id(field)) {
293
6
                    values.set_rows(field.key);
294
89
                }
295
95
                matches
296
95
                    .get_many::<Row>(field.key)
297
95
                    .into_iter()
298
95
                    .flatten()
299
51
                    .for_each(|row| values.push_row(field.key, row.clone()));
300
            }
301
204
            _ => match matches.get_one::<String>(field.key) {
302
46
                Some(text) => values.set(field.key, text),
303
158
                None if date_now && defaults_to_now(form, field) => {
304
18
                    values.set(field.key, &forms::now_instant());
305
                }
306
140
                None => {}
307
            },
308
        }
309
    }
310
68
    values
311
68
}
312

            
313
1877
fn row_keys(fields: &[Field]) -> Vec<&'static str> {
314
1877
    fields
315
1877
        .iter()
316
7665
        .filter(|field| !matches!(field.kind, Kind::Hidden))
317
7370
        .map(|field| field.key)
318
        .collect()
319
1877
}
320

            
321
/// Split on unescaped commas; `\,` and `\\` are the only escapes.
322
64
fn split_pairs(spec: &str) -> Result<Vec<String>, String> {
323
64
    let mut pairs = Vec::new();
324
64
    let mut current = String::new();
325
64
    let mut chars = spec.chars();
326
1046
    while let Some(c) = chars.next() {
327
984
        match c {
328
44
            ',' => pairs.push(std::mem::take(&mut current)),
329
6
            '\\' => match chars.next() {
330
4
                Some(escaped @ (',' | '\\')) => current.push(escaped),
331
2
                _ => return Err("a backslash must be followed by ',' or '\\'".to_string()),
332
            },
333
934
            other => current.push(other),
334
        }
335
    }
336
62
    pairs.push(current);
337
62
    Ok(pairs)
338
64
}
339

            
340
64
fn parse_row(keys: &[&str], spec: &str) -> Result<Row, String> {
341
13
    let describe = |problem: String| format!("row '{spec}': {problem}");
342
64
    let mut row = Row::new();
343
64
    for pair in split_pairs(spec).map_err(describe)? {
344
106
        let (key, value) = pair
345
106
            .split_once('=')
346
3
            .ok_or_else(|| describe(format!("expected key=value, got '{pair}'")))?;
347
103
        if !keys.contains(&key) {
348
7
            return Err(describe(format!(
349
7
                "unknown key '{key}' (expected one of: {})",
350
7
                keys.join(", ")
351
7
            )));
352
96
        }
353
96
        if row.insert(key.to_string(), value.to_string()).is_some() {
354
1
            return Err(describe(format!("duplicate key '{key}'")));
355
95
        }
356
    }
357
51
    Ok(row)
358
64
}
359

            
360
15
fn is_yes(answer: &str) -> bool {
361
15
    matches!(answer.trim().to_lowercase().as_str(), "y" | "yes")
362
15
}
363

            
364
/// Whether to go ahead: `--yes`, else the terminal's answer to `question`.
365
17
pub(crate) fn confirmed(
366
17
    question: &str,
367
17
    yes: bool,
368
17
    interactive: bool,
369
17
    mut input: impl BufRead,
370
17
) -> Result<bool, CommandError> {
371
17
    if yes {
372
3
        return Ok(true);
373
14
    }
374
14
    if !interactive {
375
4
        return Err(CommandError::Argument(
376
4
            "without a terminal, --yes is required".to_string(),
377
4
        ));
378
10
    }
379
10
    eprint!("{question} [y/N] ");
380
10
    let mut answer = String::new();
381
10
    input
382
10
        .read_line(&mut answer)
383
        .map_err(|e| CommandError::Command(format!("reading the answer: {e}")))?;
384
10
    Ok(is_yes(&answer))
385
17
}
386

            
387
pub async fn run(session: &mut Session, cmd: TransactionCmd) -> Result<(), CommandError> {
388
    match cmd {
389
        TransactionCmd::Create(values) => println!("{}", ops::create(session, &values).await?),
390
        TransactionCmd::CreateFromTemplate {
391
            template,
392
            overrides,
393
        } => println!(
394
            "{}",
395
            ops::create_from_template(session, &template.to_string(), &overrides).await?
396
        ),
397
        TransactionCmd::List(values) => {
398
            let page = ops::query(session, &values).await?;
399
            for line in ops::render_page(&page) {
400
                println!("{line}");
401
            }
402
            let [_, offset_key] = PAGING_KEYS;
403
            let offset = values.text(offset_key).and_then(|s| s.trim().parse().ok());
404
            if let Some(note) = ops::paging_note(&page, offset.unwrap_or(0)) {
405
                eprintln!("{note}");
406
            }
407
        }
408
        TransactionCmd::Show { id } => {
409
            for line in ops::show(session, &id.to_string()).await? {
410
                println!("{line}");
411
            }
412
        }
413
        TransactionCmd::Edit {
414
            id,
415
            overrides,
416
            drop_rows,
417
        } => println!(
418
            "{}",
419
            ops::edit(session, &id.to_string(), &overrides, &drop_rows).await?
420
        ),
421
        TransactionCmd::Delete { id, yes } => {
422
            let stdin = std::io::stdin();
423
            let question = format!("Delete transaction {id}?");
424
            if confirmed(&question, yes, stdin.is_terminal(), stdin.lock())? {
425
                ops::delete(session, &id.to_string()).await?;
426
            } else {
427
                eprintln!("Cancelled");
428
            }
429
        }
430
    }
431
    Ok(())
432
}
433

            
434
#[cfg(test)]
435
mod carried_tests;
436
#[cfg(test)]
437
mod choice_tests;
438
#[cfg(test)]
439
mod free_rows_tests;
440
#[cfg(test)]
441
mod split_tag_tests;
442
#[cfg(test)]
443
mod template_tests;
444
#[cfg(test)]
445
mod tests;