Skip to main content

cli/
transaction.rs

1//! `transaction` subcommands, built from the compiled-in form descriptors.
2
3use clap::builder::PossibleValuesParser;
4use clap::error::ErrorKind;
5use clap::{Arg, ArgAction, ArgMatches, Command, Error, FromArgMatches, Subcommand, value_parser};
6use cli_core::CommandError;
7use cli_core::transaction as ops;
8use forms::{Action, Field, Form, FormValues, Kind, PAGING_KEYS, Row};
9use rows_args::{
10    clear_arg, clear_id, has_clear, is_carried, is_free_rows, is_nested_tags, row_long,
11};
12use rpc::Session;
13use split_tag::{SPLIT_TAG_HELP, parse_split_tag};
14use sqlx::types::Uuid;
15use std::io::{BufRead, IsTerminal};
16
17mod rows_args;
18mod split_tag;
19
20const 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)]
27pub 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
48impl Subcommand for TransactionCmd {
49    fn augment_subcommands(cmd: Command) -> Command {
50        cmd.subcommand_required(true)
51            .arg_required_else_help(true)
52            .subcommand(create_command())
53            .subcommand(form_command(
54                "list",
55                "List transactions",
56                &forms::TRANSACTION_QUERY,
57            ))
58            .subcommand(
59                Command::new("show")
60                    .about("Show a transaction")
61                    .arg(id_arg()),
62            )
63            .subcommand(edit_command())
64            .subcommand(
65                Command::new("delete")
66                    .about("Delete a transaction")
67                    .arg(id_arg())
68                    .arg(
69                        Arg::new("yes")
70                            .long("yes")
71                            .action(ArgAction::SetTrue)
72                            .help("Delete without asking; required when stdin is not a terminal"),
73                    ),
74            )
75    }
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
86impl FromArgMatches for TransactionCmd {
87    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
88        match matches.subcommand() {
89            Some(("create", sub)) => create_of(sub),
90            Some(("list", sub)) => Ok(Self::List(values_of(&forms::TRANSACTION_QUERY, sub))),
91            Some(("show", sub)) => Ok(TransactionCmd::Show { id: id_of(sub)? }),
92            Some(("edit", sub)) => edit_of(sub),
93            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    }
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
111pub(crate) fn id_arg() -> Arg {
112    Arg::new("id")
113        .required(true)
114        .value_parser(value_parser!(Uuid))
115}
116
117pub(crate) fn id_of(sub: &ArgMatches) -> Result<Uuid, Error> {
118    sub.get_one::<Uuid>("id")
119        .copied()
120        .ok_or_else(|| Error::raw(ErrorKind::MissingRequiredArgument, "the id is required"))
121}
122
123fn delete_of(sub: &ArgMatches) -> Result<TransactionCmd, Error> {
124    Ok(TransactionCmd::Delete {
125        id: id_of(sub)?,
126        yes: sub.get_flag("yes"),
127    })
128}
129
130fn create_command() -> Command {
131    form_command("create", "Create a transaction", &forms::TRANSACTION_CREATE).arg(
132        Arg::new("template")
133            .long("template")
134            .value_name("ID")
135            .value_parser(value_parser!(Uuid))
136            .help("Start from this template's draft; the other options override it"),
137    )
138}
139
140fn create_of(sub: &ArgMatches) -> Result<TransactionCmd, Error> {
141    let form = &forms::TRANSACTION_CREATE;
142    match sub.get_one::<Uuid>("template") {
143        Some(template) => Ok(TransactionCmd::CreateFromTemplate {
144            template: *template,
145            overrides: checked_values(form, sub, false)?,
146        }),
147        None => checked_values(form, sub, true).map(TransactionCmd::Create),
148    }
149}
150
151fn edit_command() -> Command {
152    form_command(
153        "edit",
154        "Edit a transaction; omitted fields and rows stay as stored",
155        &forms::TRANSACTION_EDIT,
156    )
157    .arg(id_arg())
158    .arg(
159        Arg::new("drop-row")
160            .long("drop-row")
161            .value_name("KEY")
162            .action(ArgAction::Append)
163            .help("Remove the loaded split with this key, e.g. r2"),
164    )
165}
166
167/// The option values, refusing a `--split-tag` that names a missing `--row`.
168fn checked_values(form: &Form, sub: &ArgMatches, date_now: bool) -> Result<FormValues, Error> {
169    let values = values_with(form, sub, date_now);
170    ops::check_split_tags(&values)
171        .map_err(|e| Error::raw(ErrorKind::ValueValidation, e.to_string()))?;
172    Ok(values)
173}
174
175fn edit_of(sub: &ArgMatches) -> Result<TransactionCmd, Error> {
176    Ok(TransactionCmd::Edit {
177        id: id_of(sub)?,
178        overrides: checked_values(&forms::TRANSACTION_EDIT, sub, true)?,
179        drop_rows: sub
180            .get_many::<String>("drop-row")
181            .into_iter()
182            .flatten()
183            .cloned()
184            .collect(),
185    })
186}
187
188pub(crate) fn form_command(name: &'static str, about: &'static str, form: &Form) -> Command {
189    form.fields
190        .iter()
191        .filter(|field| !matches!(field.kind, Kind::Hidden) && !is_carried(field))
192        .fold(Command::new(name).about(about), |cmd, field| {
193            let cmd = cmd.arg(field_arg(form, field));
194            if has_clear(field) {
195                cmd.arg(clear_arg(field))
196            } else {
197                cmd
198            }
199        })
200}
201
202pub(crate) fn field_arg(form: &Form, field: &Field) -> Arg {
203    let arg = Arg::new(field.key).long(field.key).help(field.label);
204    match field.kind {
205        Kind::Rows { fields, .. } => {
206            let keys = row_keys(fields);
207            let arg = arg.long(row_long(field)).action(ArgAction::Append);
208            if is_nested_tags(field) {
209                return arg
210                    .value_name("N:NAME=VALUE[:SIDE]")
211                    .value_parser(parse_split_tag)
212                    .help(SPLIT_TAG_HELP);
213            }
214            let arg = arg
215                .value_name("KEY=VALUE,...")
216                .value_parser(move |spec: &str| parse_row(&keys, spec));
217            if is_free_rows(field) {
218                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                    field.label,
222                    row_keys(fields)
223                        .iter()
224                        .map(|k| format!("{k}=..."))
225                        .collect::<Vec<_>>()
226                        .join(","),
227                ))
228            } else {
229                arg.help(ROW_HELP)
230            }
231        }
232        Kind::Date {
233            whole_day: true, ..
234        } => arg
235            .value_name("DATE")
236            .help("A day, e.g. 2026-10-27; a range end counts through that day"),
237        Kind::Date { .. } if defaults_to_now(form, field) => arg
238            .value_name("DATE")
239            .help("Date or instant, e.g. 2026-10-27 or 2026-10-27T09:30; defaults to now"),
240        Kind::Date { .. } => arg.value_name("DATE"),
241        Kind::Choice { options, default } => choice_arg(arg, options, default),
242        _ => match page_default(form, field) {
243            Some(default) => arg.value_name(field.key).default_value(default),
244            None => arg.value_name(field.key),
245        },
246    }
247}
248
249/// Accepts only the option keys; the server fills in an omitted default.
250fn choice_arg(arg: Arg, options: &[(&'static str, &str)], default: Option<&str>) -> Arg {
251    let listed = options
252        .iter()
253        .map(|(key, label)| format!("{key} ({label})"))
254        .collect::<Vec<_>>()
255        .join(", ");
256    let help = match default {
257        Some(default) => format!("One of: {listed}; default: {default}"),
258        None => format!("One of: {listed}"),
259    };
260    arg.value_name("KEY")
261        .value_parser(PossibleValuesParser::new(
262            options.iter().map(|(key, _)| *key),
263        ))
264        .help(help)
265}
266
267/// The query form's paging defaults; also keeps an unfiltered payload non-empty.
268fn page_default(form: &Form, field: &Field) -> Option<&'static str> {
269    let [limit_key, _] = PAGING_KEYS;
270    if form.action != Action::Query || !field.is_paging() {
271        return None;
272    }
273    Some(if field.key == limit_key { "50" } else { "0" })
274}
275
276fn defaults_to_now(form: &Form, field: &Field) -> bool {
277    form.action == Action::Mutation && matches!(field.kind, Kind::Date { .. })
278}
279
280pub(crate) fn values_of(form: &Form, matches: &ArgMatches) -> FormValues {
281    values_with(form, matches, true)
282}
283
284/// The option values; an omitted mutation date is now only when `date_now`.
285fn values_with(form: &Form, matches: &ArgMatches, date_now: bool) -> FormValues {
286    let mut values = FormValues::default();
287    for field in form.fields {
288        match field.kind {
289            Kind::Hidden => {}
290            Kind::Rows { .. } if is_carried(field) => {}
291            Kind::Rows { .. } => {
292                if has_clear(field) && matches.get_flag(&clear_id(field)) {
293                    values.set_rows(field.key);
294                }
295                matches
296                    .get_many::<Row>(field.key)
297                    .into_iter()
298                    .flatten()
299                    .for_each(|row| values.push_row(field.key, row.clone()));
300            }
301            _ => match matches.get_one::<String>(field.key) {
302                Some(text) => values.set(field.key, text),
303                None if date_now && defaults_to_now(form, field) => {
304                    values.set(field.key, &forms::now_instant());
305                }
306                None => {}
307            },
308        }
309    }
310    values
311}
312
313fn row_keys(fields: &[Field]) -> Vec<&'static str> {
314    fields
315        .iter()
316        .filter(|field| !matches!(field.kind, Kind::Hidden))
317        .map(|field| field.key)
318        .collect()
319}
320
321/// Split on unescaped commas; `\,` and `\\` are the only escapes.
322fn split_pairs(spec: &str) -> Result<Vec<String>, String> {
323    let mut pairs = Vec::new();
324    let mut current = String::new();
325    let mut chars = spec.chars();
326    while let Some(c) = chars.next() {
327        match c {
328            ',' => pairs.push(std::mem::take(&mut current)),
329            '\\' => match chars.next() {
330                Some(escaped @ (',' | '\\')) => current.push(escaped),
331                _ => return Err("a backslash must be followed by ',' or '\\'".to_string()),
332            },
333            other => current.push(other),
334        }
335    }
336    pairs.push(current);
337    Ok(pairs)
338}
339
340fn parse_row(keys: &[&str], spec: &str) -> Result<Row, String> {
341    let describe = |problem: String| format!("row '{spec}': {problem}");
342    let mut row = Row::new();
343    for pair in split_pairs(spec).map_err(describe)? {
344        let (key, value) = pair
345            .split_once('=')
346            .ok_or_else(|| describe(format!("expected key=value, got '{pair}'")))?;
347        if !keys.contains(&key) {
348            return Err(describe(format!(
349                "unknown key '{key}' (expected one of: {})",
350                keys.join(", ")
351            )));
352        }
353        if row.insert(key.to_string(), value.to_string()).is_some() {
354            return Err(describe(format!("duplicate key '{key}'")));
355        }
356    }
357    Ok(row)
358}
359
360fn is_yes(answer: &str) -> bool {
361    matches!(answer.trim().to_lowercase().as_str(), "y" | "yes")
362}
363
364/// Whether to go ahead: `--yes`, else the terminal's answer to `question`.
365pub(crate) fn confirmed(
366    question: &str,
367    yes: bool,
368    interactive: bool,
369    mut input: impl BufRead,
370) -> Result<bool, CommandError> {
371    if yes {
372        return Ok(true);
373    }
374    if !interactive {
375        return Err(CommandError::Argument(
376            "without a terminal, --yes is required".to_string(),
377        ));
378    }
379    eprint!("{question} [y/N] ");
380    let mut answer = String::new();
381    input
382        .read_line(&mut answer)
383        .map_err(|e| CommandError::Command(format!("reading the answer: {e}")))?;
384    Ok(is_yes(&answer))
385}
386
387pub 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)]
435mod carried_tests;
436#[cfg(test)]
437mod choice_tests;
438#[cfg(test)]
439mod free_rows_tests;
440#[cfg(test)]
441mod split_tag_tests;
442#[cfg(test)]
443mod template_tests;
444#[cfg(test)]
445mod tests;