1
//! Create, edit, convert and config subcommands, built from the compiled-in form descriptors.
2

            
3
use clap::error::ErrorKind;
4
use clap::{ArgMatches, Command, Error, FromArgMatches, Subcommand};
5
use cli_core::CommandError;
6
use cli_core::flat::{self, Reply};
7
use forms::{Action, Form, FormValues};
8
use rpc::Session;
9
use sqlx::types::Uuid;
10
use std::io::BufRead;
11

            
12
use crate::eval::{RenderMode, build_delete_tag_form, eval_print};
13
use crate::transaction::{confirmed, form_command, id_arg, id_of, values_of};
14

            
15
#[derive(Debug)]
16
pub struct FormCall {
17
    form: &'static Form,
18
    id: Option<Uuid>,
19
    values: FormValues,
20
}
21

            
22
pub struct Entry {
23
    name: &'static str,
24
    about: &'static str,
25
    form: &'static Form,
26
}
27

            
28
pub 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

            
41
pub 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

            
59
pub 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

            
72
pub const CONFIG_FORMS: [Entry; 1] = [Entry {
73
    name: "set",
74
    about: "Set the value in config",
75
    form: &forms::CONFIG_SET,
76
}];
77

            
78
912
fn entry_command(entry: &Entry) -> Command {
79
912
    let command = form_command(entry.name, entry.about, entry.form);
80
912
    match entry.form.action {
81
342
        Action::LoadMutation => command.arg(id_arg()),
82
570
        _ => command,
83
    }
84
912
}
85

            
86
452
fn augment(cmd: Command, entries: &[Entry]) -> Command {
87
452
    entries
88
452
        .iter()
89
904
        .fold(cmd, |cmd, entry| cmd.subcommand(entry_command(entry)))
90
452
}
91

            
92
9
fn parse(matches: &ArgMatches, entries: &[Entry]) -> Result<FormCall, Error> {
93
9
    let (name, sub) = matches
94
9
        .subcommand()
95
        .ok_or_else(|| Error::raw(ErrorKind::MissingSubcommand, "a subcommand is required"))?;
96
9
    let entry = entries
97
9
        .iter()
98
14
        .find(|entry| entry.name == name)
99
        .ok_or_else(|| {
100
            Error::raw(
101
                ErrorKind::InvalidSubcommand,
102
                format!("unknown subcommand '{name}'"),
103
            )
104
        })?;
105
9
    let id = match entry.form.action {
106
3
        Action::LoadMutation => Some(id_of(sub)?),
107
6
        _ => None,
108
    };
109
9
    Ok(FormCall {
110
9
        form: entry.form,
111
9
        id,
112
9
        values: values_of(entry.form, sub),
113
9
    })
114
9
}
115

            
116
macro_rules! form_group {
117
    ($group:ident, $entries:expr) => {
118
        #[derive(Debug)]
119
        pub struct $group(pub FormCall);
120

            
121
        impl Subcommand for $group {
122
452
            fn augment_subcommands(cmd: Command) -> Command {
123
452
                augment(cmd, &$entries)
124
452
            }
125

            
126
            fn augment_subcommands_for_update(cmd: Command) -> Command {
127
                augment(cmd, &$entries)
128
            }
129

            
130
17
            fn has_subcommand(name: &str) -> bool {
131
29
                $entries.iter().any(|entry| entry.name == name)
132
17
            }
133
        }
134

            
135
        impl FromArgMatches for $group {
136
9
            fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
137
9
                parse(matches, &$entries).map(Self)
138
9
            }
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

            
148
form_group!(AccountForms, ACCOUNT_FORMS);
149
form_group!(CommodityForms, COMMODITY_FORMS);
150
form_group!(TagForms, TAG_FORMS);
151
form_group!(ConfigForms, CONFIG_FORMS);
152

            
153
1
fn converted_line(values: &FormValues, converted: &str) -> String {
154
3
    let text = |key| values.text(key).unwrap_or_default();
155
1
    format!(
156
1
        "{} {} = {converted} {}",
157
1
        text("amount"),
158
1
        text("from"),
159
1
        text("to")
160
    )
161
1
}
162

            
163
3
fn printed(values: &FormValues, reply: &Reply) -> Option<String> {
164
3
    match reply {
165
1
        Reply::Entity(id) => Some(id.clone()),
166
1
        Reply::Done => None,
167
1
        Reply::Value(converted) => Some(converted_line(values, converted)),
168
    }
169
3
}
170

            
171
impl AccountForms {
172
    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
173
        run(session, self.0).await
174
    }
175
}
176

            
177
impl CommodityForms {
178
    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
179
        run(session, self.0).await
180
    }
181
}
182

            
183
impl TagForms {
184
    pub async fn run(self, session: &mut Session) -> Result<(), CommandError> {
185
        run(session, self.0).await
186
    }
187
}
188

            
189
impl 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.
196
4
pub async fn delete_tag_confirmed(
197
4
    session: &mut Session,
198
4
    id: Uuid,
199
4
    yes: bool,
200
4
    interactive: bool,
201
4
    input: impl BufRead,
202
4
) -> Result<bool, CommandError> {
203
4
    let question = format!("Delete tag {id} and every link to it?");
204
4
    if !confirmed(&question, yes, interactive, input)? {
205
1
        return Ok(false);
206
2
    }
207
2
    let form = build_delete_tag_form(&id.to_string());
208
2
    eval_print(session, &form, RenderMode::BoolSuccess).await?;
209
2
    Ok(true)
210
4
}
211

            
212
async 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)]
227
pub(crate) mod tests;