Skip to main content

cli/
flat.rs

1//! Create, edit, convert and config subcommands, built from the compiled-in form descriptors.
2
3use clap::error::ErrorKind;
4use clap::{ArgMatches, Command, Error, FromArgMatches, Subcommand};
5use cli_core::CommandError;
6use cli_core::flat::{self, Reply};
7use forms::{Action, Form, FormValues};
8use rpc::Session;
9use sqlx::types::Uuid;
10use std::io::BufRead;
11
12use crate::eval::{RenderMode, build_delete_tag_form, eval_print};
13use crate::transaction::{confirmed, form_command, id_arg, id_of, values_of};
14
15#[derive(Debug)]
16pub struct FormCall {
17    form: &'static Form,
18    id: Option<Uuid>,
19    values: FormValues,
20}
21
22pub struct Entry {
23    name: &'static str,
24    about: &'static str,
25    form: &'static Form,
26}
27
28pub const ACCOUNT_FORMS: [Entry; 2] = [
29    Entry {
30        name: "create",
31        about: "Create new account",
32        form: &forms::ACCOUNT_CREATE,
33    },
34    Entry {
35        name: "edit",
36        about: "Edit an account; omitted fields stay as stored",
37        form: &forms::ACCOUNT_EDIT,
38    },
39];
40
41pub const COMMODITY_FORMS: [Entry; 3] = [
42    Entry {
43        name: "create",
44        about: "Create new commodity",
45        form: &forms::COMMODITY_CREATE,
46    },
47    Entry {
48        name: "edit",
49        about: "Edit a commodity; omitted fields stay as stored",
50        form: &forms::COMMODITY_EDIT,
51    },
52    Entry {
53        name: "convert",
54        about: "Convert an amount between commodities with the latest price",
55        form: &forms::CONVERT,
56    },
57];
58
59pub const TAG_FORMS: [Entry; 2] = [
60    Entry {
61        name: "create",
62        about: "Create new tag",
63        form: &forms::TAG_CREATE,
64    },
65    Entry {
66        name: "edit",
67        about: "Edit a tag; omitted fields stay as stored",
68        form: &forms::TAG_EDIT,
69    },
70];
71
72pub const CONFIG_FORMS: [Entry; 1] = [Entry {
73    name: "set",
74    about: "Set the value in config",
75    form: &forms::CONFIG_SET,
76}];
77
78fn entry_command(entry: &Entry) -> Command {
79    let command = form_command(entry.name, entry.about, entry.form);
80    match entry.form.action {
81        Action::LoadMutation => command.arg(id_arg()),
82        _ => command,
83    }
84}
85
86fn augment(cmd: Command, entries: &[Entry]) -> Command {
87    entries
88        .iter()
89        .fold(cmd, |cmd, entry| cmd.subcommand(entry_command(entry)))
90}
91
92fn parse(matches: &ArgMatches, entries: &[Entry]) -> Result<FormCall, Error> {
93    let (name, sub) = matches
94        .subcommand()
95        .ok_or_else(|| Error::raw(ErrorKind::MissingSubcommand, "a subcommand is required"))?;
96    let entry = entries
97        .iter()
98        .find(|entry| entry.name == name)
99        .ok_or_else(|| {
100            Error::raw(
101                ErrorKind::InvalidSubcommand,
102                format!("unknown subcommand '{name}'"),
103            )
104        })?;
105    let id = match entry.form.action {
106        Action::LoadMutation => Some(id_of(sub)?),
107        _ => None,
108    };
109    Ok(FormCall {
110        form: entry.form,
111        id,
112        values: values_of(entry.form, sub),
113    })
114}
115
116macro_rules! form_group {
117    ($group:ident, $entries:expr) => {
118        #[derive(Debug)]
119        pub struct $group(pub FormCall);
120
121        impl Subcommand for $group {
122            fn augment_subcommands(cmd: Command) -> Command {
123                augment(cmd, &$entries)
124            }
125
126            fn augment_subcommands_for_update(cmd: Command) -> Command {
127                augment(cmd, &$entries)
128            }
129
130            fn has_subcommand(name: &str) -> bool {
131                $entries.iter().any(|entry| entry.name == name)
132            }
133        }
134
135        impl FromArgMatches for $group {
136            fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
137                parse(matches, &$entries).map(Self)
138            }
139
140            fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
141                *self = Self::from_arg_matches(matches)?;
142                Ok(())
143            }
144        }
145    };
146}
147
148form_group!(AccountForms, ACCOUNT_FORMS);
149form_group!(CommodityForms, COMMODITY_FORMS);
150form_group!(TagForms, TAG_FORMS);
151form_group!(ConfigForms, CONFIG_FORMS);
152
153fn converted_line(values: &FormValues, converted: &str) -> String {
154    let text = |key| values.text(key).unwrap_or_default();
155    format!(
156        "{} {} = {converted} {}",
157        text("amount"),
158        text("from"),
159        text("to")
160    )
161}
162
163fn printed(values: &FormValues, reply: &Reply) -> Option<String> {
164    match reply {
165        Reply::Entity(id) => Some(id.clone()),
166        Reply::Done => None,
167        Reply::Value(converted) => Some(converted_line(values, converted)),
168    }
169}
170
171impl AccountForms {
172    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
173        run(session, self.0).await
174    }
175}
176
177impl CommodityForms {
178    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
179        run(session, self.0).await
180    }
181}
182
183impl TagForms {
184    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
185        run(session, self.0).await
186    }
187}
188
189impl ConfigForms {
190    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
191        run(session, self.0).await
192    }
193}
194
195/// Deletes the tag unless the answer declines; returns whether it was deleted.
196pub async fn delete_tag_confirmed(
197    session: &mut Session,
198    id: Uuid,
199    yes: bool,
200    interactive: bool,
201    input: impl BufRead,
202) -> Result<bool, CommandError> {
203    let question = format!("Delete tag {id} and every link to it?");
204    if !confirmed(&question, yes, interactive, input)? {
205        return Ok(false);
206    }
207    let form = build_delete_tag_form(&id.to_string());
208    eval_print(session, &form, RenderMode::BoolSuccess).await?;
209    Ok(true)
210}
211
212async fn run(session: &mut Session, call: FormCall) -> Result<(), CommandError> {
213    let submitted = match call.id {
214        Some(id) => flat::edit(session, call.form, &id.to_string(), &call.values).await?,
215        None => flat::submit(session, call.form, &call.values).await?,
216    };
217    if let Some(line) = printed(&call.values, &submitted.reply) {
218        println!("{line}");
219    }
220    for notice in submitted.notices {
221        eprintln!("notice: {notice}");
222    }
223    Ok(())
224}
225
226#[cfg(test)]
227pub(crate) mod tests;