1
//! `reports` subcommands, built from the compiled-in report descriptors.
2

            
3
use std::io::IsTerminal;
4
use std::path::{Path, PathBuf};
5

            
6
use clap::error::ErrorKind;
7
use clap::{Arg, ArgAction, ArgMatches, Command, Error, FromArgMatches, Subcommand};
8
use cli_core::CommandError;
9
use cli_core::eval::Rendered;
10
use cli_core::report_form::{self, ChartRequest, ChartSize};
11
use forms::{Form, FormValues};
12
use rpc::Session;
13
use rpc::chart::{ChartFormat, ChartLook, DEFAULT_HEIGHT, DEFAULT_WIDTH, MAX_SIDE, parse_kind};
14

            
15
use crate::eval::print_rendered;
16
use crate::transaction::{form_command, values_of};
17

            
18
const CHART: &str = "chart";
19
const PNG: &str = "png";
20
const SVG: &str = "svg";
21
const SIZE: &str = "size";
22
const CSV: &str = "csv";
23
const DEFAULT_CHART: &str = "bar";
24

            
25
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26
enum Report {
27
    Balance,
28
    Activity,
29
    Breakdown,
30
}
31

            
32
const REPORTS: [(Report, &str, &str); 3] = [
33
    (
34
        Report::Balance,
35
        "balance",
36
        "Balance chart (top-level accounts by magnitude)",
37
    ),
38
    (
39
        Report::Activity,
40
        "activity",
41
        "Activity chart (Income vs Expense over a period)",
42
    ),
43
    (
44
        Report::Breakdown,
45
        "breakdown",
46
        "Category breakdown chart (top-N tag values)",
47
    ),
48
];
49

            
50
impl Report {
51
430
    fn form(self) -> &'static Form {
52
430
        match self {
53
153
            Self::Balance => &forms::REPORT_BALANCE,
54
138
            Self::Activity => &forms::REPORT_ACTIVITY,
55
139
            Self::Breakdown => &forms::REPORT_CATEGORY,
56
        }
57
430
    }
58
}
59

            
60
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61
enum Renderer {
62
    Text,
63
    Kitty,
64
}
65

            
66
/// What `--chart` names: a chart shape, or a terminal renderer drawing the bar chart.
67
#[derive(Debug, PartialEq, Eq)]
68
struct ChartChoice {
69
    kind: String,
70
    renderer: Option<Renderer>,
71
}
72

            
73
impl ChartChoice {
74
25
    fn parse(name: &str) -> Result<Self, Error> {
75
25
        let renderer = match name.to_ascii_lowercase().as_str() {
76
4
            "text" | "ascii" => Some(Renderer::Text),
77
3
            "kitty" | "graphic" => Some(Renderer::Kitty),
78
18
            _ => None,
79
        };
80
25
        if renderer.is_none() && parse_kind(name).is_none() {
81
1
            return Err(Error::raw(
82
1
                ErrorKind::InvalidValue,
83
1
                format!("unknown chart '{name}': use bar, line, stacked, text or kitty"),
84
1
            ));
85
24
        }
86
24
        let kind = if renderer.is_some() { "bar" } else { name };
87
24
        Ok(Self {
88
24
            kind: kind.to_string(),
89
24
            renderer,
90
24
        })
91
25
    }
92
}
93

            
94
#[derive(Debug)]
95
pub struct ReportsCmd {
96
    report: Report,
97
    values: FormValues,
98
    chart: ChartChoice,
99
    png: Option<PathBuf>,
100
    svg: Option<PathBuf>,
101
    size: ChartSize,
102
    csv: bool,
103
}
104

            
105
20
fn defaulted<'a, T: Clone + Send + Sync + 'static>(
106
20
    matches: &'a ArgMatches,
107
20
    id: &str,
108
20
) -> Result<&'a T, Error> {
109
20
    matches.get_one::<T>(id).ok_or_else(|| {
110
        Error::raw(
111
            ErrorKind::MissingRequiredArgument,
112
            format!("--{id} has no value"),
113
        )
114
    })
115
20
}
116

            
117
63
fn parse_side(text: &str) -> Result<u32, String> {
118
63
    text.parse::<u32>()
119
63
        .ok()
120
61
        .filter(|side| (1..=MAX_SIDE).contains(side))
121
6
        .ok_or_else(|| format!("'{text}' is not a size from 1 to {MAX_SIDE}"))
122
63
}
123

            
124
34
fn parse_size(text: &str) -> Result<ChartSize, String> {
125
34
    let (width, height) = text
126
34
        .split_once('x')
127
1
        .ok_or_else(|| format!("'{text}' is not WIDTHxHEIGHT"))?;
128
33
    Ok((parse_side(width)?, parse_side(height)?))
129
34
}
130

            
131
402
fn report_command(report: Report, name: &'static str, about: &'static str) -> Command {
132
402
    let command = form_command(name, about, report.form());
133
402
    let command = match report {
134
134
        Report::Breakdown => command.arg(
135
134
            Arg::new(CSV)
136
134
                .long(CSV)
137
134
                .action(ArgAction::SetTrue)
138
134
                .conflicts_with_all([CHART, PNG, SVG, SIZE])
139
134
                .help("Print the report as CSV on stdout instead of a chart"),
140
134
        ),
141
268
        Report::Balance | Report::Activity => command,
142
    };
143
402
    command
144
402
        .arg(
145
402
            Arg::new(CHART)
146
402
                .long(CHART)
147
402
                .default_value(DEFAULT_CHART)
148
402
                .help("Chart shape or renderer: bar, line, stacked, text, kitty"),
149
402
        )
150
402
        .arg(
151
402
            Arg::new(PNG)
152
402
                .long(PNG)
153
402
                .value_name("FILE")
154
402
                .value_parser(clap::value_parser!(PathBuf))
155
402
                .help("Write the chart as a PNG file; nothing is printed"),
156
402
        )
157
402
        .arg(
158
402
            Arg::new(SVG)
159
402
                .long(SVG)
160
402
                .value_name("FILE")
161
402
                .value_parser(clap::value_parser!(PathBuf))
162
402
                .help("Write the chart as an SVG file; nothing is printed"),
163
402
        )
164
402
        .arg(
165
402
            Arg::new(SIZE)
166
402
                .long(SIZE)
167
402
                .value_name("WxH")
168
402
                .default_value(format!("{DEFAULT_WIDTH}x{DEFAULT_HEIGHT}"))
169
402
                .value_parser(parse_size)
170
402
                .help("Chart size in pixels, each side 1 to 2048"),
171
402
        )
172
402
}
173

            
174
impl Subcommand for ReportsCmd {
175
134
    fn augment_subcommands(cmd: Command) -> Command {
176
134
        REPORTS.iter().fold(
177
134
            cmd.subcommand_required(true).arg_required_else_help(true),
178
402
            |cmd, (report, name, about)| cmd.subcommand(report_command(*report, name, about)),
179
        )
180
134
    }
181

            
182
    fn augment_subcommands_for_update(cmd: Command) -> Command {
183
        Self::augment_subcommands(cmd)
184
    }
185

            
186
    fn has_subcommand(name: &str) -> bool {
187
        REPORTS.iter().any(|(_, known, _)| *known == name)
188
    }
189
}
190

            
191
impl FromArgMatches for ReportsCmd {
192
25
    fn from_arg_matches(matches: &ArgMatches) -> Result<Self, Error> {
193
25
        let (name, sub) = matches
194
25
            .subcommand()
195
            .ok_or_else(|| Error::raw(ErrorKind::MissingSubcommand, "a report name is required"))?;
196
25
        let (report, ..) = REPORTS
197
25
            .iter()
198
36
            .find(|(_, known, _)| *known == name)
199
            .ok_or_else(|| {
200
                Error::raw(
201
                    ErrorKind::InvalidSubcommand,
202
                    format!("unknown report '{name}'"),
203
                )
204
            })?;
205
25
        let chart = ChartChoice::parse(sub.get_one::<String>(CHART).map_or("bar", String::as_str))?;
206
24
        let (png, svg) = (
207
24
            sub.get_one::<PathBuf>(PNG).cloned(),
208
24
            sub.get_one::<PathBuf>(SVG).cloned(),
209
24
        );
210
24
        if chart.renderer.is_some() && (png.is_some() || svg.is_some()) {
211
4
            return Err(Error::raw(
212
4
                ErrorKind::ArgumentConflict,
213
4
                "--png and --svg draw a bar, line or stacked chart, not text or kitty".to_string(),
214
4
            ));
215
20
        }
216
        Ok(Self {
217
20
            report: *report,
218
20
            values: values_of(report.form(), sub),
219
20
            chart,
220
20
            png,
221
20
            svg,
222
20
            size: *defaulted::<ChartSize>(sub, SIZE)?,
223
20
            csv: sub.try_get_one::<bool>(CSV).ok().flatten() == Some(&true),
224
        })
225
25
    }
226

            
227
    fn update_from_arg_matches(&mut self, matches: &ArgMatches) -> Result<(), Error> {
228
        *self = Self::from_arg_matches(matches)?;
229
        Ok(())
230
    }
231
}
232

            
233
11
fn wants_kitty(
234
11
    renderer: Option<Renderer>,
235
11
    tty: bool,
236
11
    env: impl Fn(&str) -> Option<String>,
237
11
) -> bool {
238
11
    match renderer {
239
2
        Some(Renderer::Kitty) => tty,
240
2
        Some(Renderer::Text) => false,
241
7
        None => tty && rpc::chart::env_speaks_kitty(env),
242
    }
243
11
}
244

            
245
1
fn use_kitty(renderer: Option<Renderer>) -> bool {
246
1
    wants_kitty(renderer, std::io::stdout().is_terminal(), |name| {
247
        std::env::var(name).ok()
248
    })
249
1
}
250

            
251
4
fn write_file(path: &Path, bytes: &[u8]) -> Result<(), CommandError> {
252
4
    std::fs::write(path, bytes)
253
1
        .map_err(|e| CommandError::Command(format!("{}: {e}", path.display())))
254
4
}
255

            
256
3
async fn write_files(session: &mut Session, cmd: &ReportsCmd) -> Result<(), CommandError> {
257
3
    let (form, kind) = (cmd.report.form(), cmd.chart.kind.as_str());
258
3
    if let Some(path) = &cmd.png {
259
2
        let png = report_form::chart_png(session, form, &cmd.values, kind, cmd.size).await?;
260
2
        write_file(path, &png)?;
261
1
    }
262
3
    if let Some(path) = &cmd.svg {
263
2
        let request = ChartRequest {
264
2
            kind,
265
2
            format: ChartFormat::Svg,
266
2
            size: cmd.size,
267
2
            look: ChartLook::default(),
268
2
        };
269
2
        let svg = report_form::chart(session, form, &cmd.values, &request).await?;
270
2
        write_file(path, svg.as_bytes())?;
271
1
    }
272
2
    Ok(())
273
3
}
274

            
275
4
async fn render(session: &mut Session, cmd: &ReportsCmd) -> Result<Rendered, CommandError> {
276
4
    if cmd.csv {
277
        let csv = report_form::csv(session, cmd.report.form(), &cmd.values).await?;
278
        return Ok(Rendered::Bytes(csv.into_bytes()));
279
4
    }
280
4
    if cmd.png.is_some() || cmd.svg.is_some() {
281
3
        write_files(session, cmd).await?;
282
2
        return Ok(Rendered::Nothing);
283
1
    }
284
1
    report_form::terminal_chart(
285
1
        session,
286
1
        cmd.report.form(),
287
1
        &cmd.values,
288
1
        &cmd.chart.kind,
289
1
        use_kitty(cmd.chart.renderer),
290
1
        cmd.size,
291
1
    )
292
1
    .await
293
4
}
294

            
295
pub async fn run(session: &mut Session, cmd: ReportsCmd) -> Result<(), CommandError> {
296
    print_rendered(render(session, &cmd).await?)
297
}
298

            
299
#[cfg(test)]
300
mod chart_tests;
301
#[cfg(test)]
302
mod tests;