1
//! Reports tab: balance / activity / category-breakdown.
2
//!
3
//! `ReportsTab` holds the current fetch state and the last successful table.
4
//! `on_reply` parses a wire frame with the shared `cli_core::reports` helpers
5
//! and lays the reply's rows out as an exact table (`table`).
6

            
7
use chart::ChartPane;
8
use cli_core::CommandError;
9
use cli_core::render::{WireValue, parse_wire};
10
use cli_core::reports::{
11
    value_to_activity_periods, value_to_balance_rows, value_to_breakdown_periods,
12
};
13
use forms::{FormValues, Kind};
14
use ratatui::buffer::Buffer;
15
use ratatui::layout::Rect;
16
use ratatui::widgets::{Paragraph, Widget};
17
use tvui::{
18
    Chrome, Panel, RowWindow, inner, range_text, render_info, render_scrollbar, scrollbar_parts,
19
};
20

            
21
use crate::event::Intent;
22
use crate::hits::{Surface, Target};
23
use crate::scroll;
24
use crate::tabs::fetch::Fetch;
25
use crate::tabs::seq::Seq;
26
use crate::view::DrawCtx;
27
use table::{activity_table, balance_table, breakdown_table};
28

            
29
/// Which report is currently loaded or being fetched.
30
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31
pub enum ReportKind {
32
    Balance,
33
    Activity,
34
    Breakdown,
35
}
36

            
37
impl ReportKind {
38
    pub const ALL: [Self; 3] = [Self::Balance, Self::Activity, Self::Breakdown];
39

            
40
    /// The shared form descriptor that sets this report up.
41
    #[must_use]
42
1372
    pub fn descriptor(self) -> &'static forms::Form {
43
1372
        match self {
44
977
            ReportKind::Balance => &forms::REPORT_BALANCE,
45
264
            ReportKind::Activity => &forms::REPORT_ACTIVITY,
46
131
            ReportKind::Breakdown => &forms::REPORT_CATEGORY,
47
        }
48
1372
    }
49

            
50
    #[must_use]
51
794
    pub fn label(self) -> &'static str {
52
794
        match self {
53
779
            ReportKind::Balance => "Balance",
54
6
            ReportKind::Activity => "Activity",
55
9
            ReportKind::Breakdown => "Category Breakdown",
56
        }
57
794
    }
58
}
59

            
60
pub struct ReportsTab {
61
    pub state: Fetch<Vec<String>>,
62
    /// First table line shown.
63
    pub scroll: RowWindow,
64
    /// Which report produced the current (or pending) fetch.
65
    pub kind: ReportKind,
66
    /// The last accepted report with the exact values it ran with.
67
    last: Option<(ReportKind, FormValues)>,
68
    /// The report the table or loading state belongs to.
69
    shown: Option<(ReportKind, FormValues)>,
70
    pub chart: ChartPane,
71
    pub run_seq: Seq,
72
    pub csv_seq: Seq,
73
}
74

            
75
impl ReportsTab {
76
    #[must_use]
77
2079
    pub fn new() -> Self {
78
2079
        Self {
79
2079
            state: Fetch::Idle,
80
2079
            scroll: RowWindow::default(),
81
2079
            kind: ReportKind::Balance,
82
2079
            last: None,
83
2079
            shown: None,
84
2079
            chart: ChartPane::new(),
85
2079
            run_seq: Seq::default(),
86
2079
            csv_seq: Seq::default(),
87
2079
        }
88
2079
    }
89

            
90
    /// Scroll by the intent's step; other intents are not scrolling.
91
    #[must_use]
92
224
    pub fn scroll_by(&self, intent: Intent) -> bool {
93
224
        scroll::apply(&self.scroll, intent)
94
224
    }
95

            
96
    /// Set loading state once an eval id is assigned.
97
36
    pub fn set_loading(&mut self, id: i64, kind: ReportKind, values: &FormValues) {
98
36
        self.kind = kind;
99
36
        self.shown = Some((kind, values.clone()));
100
36
        self.scroll.reset();
101
36
        self.state = Fetch::Loading { id };
102
36
    }
103

            
104
    /// Apply a routed reply, parsing it with the `kind` that produced the
105
    /// request (carried on the route), not the tab's current selection — the
106
    /// two can differ if a newer request was issued before this reply.
107
    /// Only an accepted reply makes `values` the report to re-run and re-edit.
108
125
    pub fn on_reply(&mut self, wire: &str, kind: ReportKind, values: FormValues) {
109
125
        self.kind = kind;
110
125
        self.scroll.reset();
111
125
        self.state = parse_report_reply(wire, kind);
112
125
        if !matches!(self.state, Fetch::Error(_)) {
113
120
            self.shown = Some((kind, values));
114
120
            self.last.clone_from(&self.shown);
115
5
        }
116
125
    }
117

            
118
    /// Drop the loading state of a run that a newer one superseded.
119
132
    pub fn abandon_loading(&mut self) {
120
132
        if matches!(self.state, Fetch::Loading { .. }) {
121
1
            self.state = Fetch::Idle;
122
131
        }
123
132
    }
124

            
125
    #[must_use]
126
135
    pub fn last(&self) -> Option<&(ReportKind, FormValues)> {
127
135
        self.last.as_ref()
128
135
    }
129

            
130
    /// The shown report's label and its date values, e.g. `Activity from=2026-01-01`.
131
791
    pub fn title(&self) -> String {
132
791
        let Some((kind, values)) = &self.shown else {
133
489
            return self.kind.label().to_string();
134
        };
135
1250
        let dates = kind.descriptor().fields.iter().filter_map(|field| {
136
1250
            let text = values.text(field.key).filter(|text| !text.is_empty())?;
137
314
            matches!(field.kind, Kind::Date { .. }).then(|| format!("{}={text}", field.key))
138
1250
        });
139
302
        std::iter::once(kind.label().to_string())
140
302
            .chain(dates)
141
302
            .collect::<Vec<_>>()
142
302
            .join(" ")
143
791
    }
144

            
145
    #[must_use]
146
281
    pub fn table_loaded(&self) -> bool {
147
281
        matches!(self.state, Fetch::Loaded(_))
148
281
    }
149

            
150
    /// Whether the chart replaces the table: only over a table that is loaded.
151
    #[must_use]
152
474
    pub fn chart_visible(&self) -> bool {
153
474
        self.chart.shown() && self.table_loaded()
154
474
    }
155

            
156
    /// Render the tab into `area`.
157
190
    pub fn draw(&self, buf: &mut Buffer, area: Rect, ctx: &mut DrawCtx) {
158
190
        Chrome::new(ctx.theme, &ctx.title, ctx.frame).render(area, buf);
159
190
        if self.chart_visible() {
160
126
            return self.chart.draw(buf, inner(area), ctx);
161
64
        }
162
64
        let text = match &self.state {
163
3
            Fetch::Idle => "b/a/c open a report form; or :reports balance | :reports activity from=YYYY-MM-DD to=YYYY-MM-DD | :reports breakdown from=... to=...".to_string(),
164
8
            Fetch::Loading { .. } => "Loading...".to_string(),
165
            Fetch::Error(e) => format!("[error] {e}"),
166
53
            Fetch::Loaded(lines) => return self.draw_table(buf, area, lines, ctx),
167
        };
168
11
        Paragraph::new(text).render(inner(area), buf);
169
190
    }
170

            
171
53
    fn draw_table(&self, buf: &mut Buffer, area: Rect, lines: &[String], ctx: &mut DrawCtx) {
172
53
        let rows = lines.len();
173
53
        let view = usize::from(Panel::inner(area).height);
174
53
        let top = self.scroll.fit(rows, view);
175
53
        let scroll = u16::try_from(top).unwrap_or(u16::MAX);
176
53
        let table = Paragraph::new(lines.join("\n")).scroll((scroll, 0));
177
53
        table.render(inner(area), buf);
178
53
        let shown = top..(top + view).min(rows);
179
53
        if let Some(info) = range_text(shown, rows).filter(|_| rows > view) {
180
29
            render_info(ctx.theme, area, buf, ctx.frame, &info);
181
24
        }
182
53
        render_scrollbar(ctx.theme, area, buf, (rows, view, top));
183
53
        ctx.hits
184
53
            .push(Panel::inner(area), Target::Body(Surface::Pane));
185
53
        for (rect, part) in scrollbar_parts(area, (rows, view, top)) {
186
122
            ctx.hits.push(rect, Target::Scroll(Surface::Pane, part));
187
        }
188
53
    }
189
}
190

            
191
impl Default for ReportsTab {
192
    fn default() -> Self {
193
        Self::new()
194
    }
195
}
196

            
197
/// Parse a wire reply frame into the table lines for the given kind.
198
125
fn parse_report_reply(wire: &str, kind: ReportKind) -> Fetch<Vec<String>> {
199
125
    match parse_wire(wire) {
200
4
        Err(e) => Fetch::Error(e.to_string()),
201
121
        Ok(WireValue::Value(value)) => match build_table(&value, kind) {
202
120
            Ok(lines) => Fetch::Loaded(lines),
203
1
            Err(e) => Fetch::Error(e.to_string()),
204
        },
205
    }
206
125
}
207

            
208
121
fn build_table(
209
121
    value: &scripting::nomiscript::Value,
210
121
    kind: ReportKind,
211
121
) -> Result<Vec<String>, CommandError> {
212
121
    Ok(match kind {
213
85
        ReportKind::Balance => balance_table(&value_to_balance_rows(value)?),
214
12
        ReportKind::Activity => activity_table(&value_to_activity_periods(value)?),
215
24
        ReportKind::Breakdown => breakdown_table(&value_to_breakdown_periods(value)?),
216
    })
217
121
}
218

            
219
pub mod chart;
220
pub(crate) mod table;
221

            
222
#[cfg(test)]
223
mod tests;
224

            
225
#[cfg(test)]
226
mod table_tests;