1use chart::ChartPane;
8use cli_core::CommandError;
9use cli_core::render::{WireValue, parse_wire};
10use cli_core::reports::{
11 value_to_activity_periods, value_to_balance_rows, value_to_breakdown_periods,
12};
13use forms::{FormValues, Kind};
14use ratatui::buffer::Buffer;
15use ratatui::layout::Rect;
16use ratatui::widgets::{Paragraph, Widget};
17use tvui::{
18 Chrome, Panel, RowWindow, inner, range_text, render_info, render_scrollbar, scrollbar_parts,
19};
20
21use crate::event::Intent;
22use crate::hits::{Surface, Target};
23use crate::scroll;
24use crate::tabs::fetch::Fetch;
25use crate::tabs::seq::Seq;
26use crate::view::DrawCtx;
27use table::{activity_table, balance_table, breakdown_table};
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum ReportKind {
32 Balance,
33 Activity,
34 Breakdown,
35}
36
37impl ReportKind {
38 pub const ALL: [Self; 3] = [Self::Balance, Self::Activity, Self::Breakdown];
39
40 #[must_use]
42 pub fn descriptor(self) -> &'static forms::Form {
43 match self {
44 ReportKind::Balance => &forms::REPORT_BALANCE,
45 ReportKind::Activity => &forms::REPORT_ACTIVITY,
46 ReportKind::Breakdown => &forms::REPORT_CATEGORY,
47 }
48 }
49
50 #[must_use]
51 pub fn label(self) -> &'static str {
52 match self {
53 ReportKind::Balance => "Balance",
54 ReportKind::Activity => "Activity",
55 ReportKind::Breakdown => "Category Breakdown",
56 }
57 }
58}
59
60pub struct ReportsTab {
61 pub state: Fetch<Vec<String>>,
62 pub scroll: RowWindow,
64 pub kind: ReportKind,
66 last: Option<(ReportKind, FormValues)>,
68 shown: Option<(ReportKind, FormValues)>,
70 pub chart: ChartPane,
71 pub run_seq: Seq,
72 pub csv_seq: Seq,
73}
74
75impl ReportsTab {
76 #[must_use]
77 pub fn new() -> Self {
78 Self {
79 state: Fetch::Idle,
80 scroll: RowWindow::default(),
81 kind: ReportKind::Balance,
82 last: None,
83 shown: None,
84 chart: ChartPane::new(),
85 run_seq: Seq::default(),
86 csv_seq: Seq::default(),
87 }
88 }
89
90 #[must_use]
92 pub fn scroll_by(&self, intent: Intent) -> bool {
93 scroll::apply(&self.scroll, intent)
94 }
95
96 pub fn set_loading(&mut self, id: i64, kind: ReportKind, values: &FormValues) {
98 self.kind = kind;
99 self.shown = Some((kind, values.clone()));
100 self.scroll.reset();
101 self.state = Fetch::Loading { id };
102 }
103
104 pub fn on_reply(&mut self, wire: &str, kind: ReportKind, values: FormValues) {
109 self.kind = kind;
110 self.scroll.reset();
111 self.state = parse_report_reply(wire, kind);
112 if !matches!(self.state, Fetch::Error(_)) {
113 self.shown = Some((kind, values));
114 self.last.clone_from(&self.shown);
115 }
116 }
117
118 pub fn abandon_loading(&mut self) {
120 if matches!(self.state, Fetch::Loading { .. }) {
121 self.state = Fetch::Idle;
122 }
123 }
124
125 #[must_use]
126 pub fn last(&self) -> Option<&(ReportKind, FormValues)> {
127 self.last.as_ref()
128 }
129
130 pub fn title(&self) -> String {
132 let Some((kind, values)) = &self.shown else {
133 return self.kind.label().to_string();
134 };
135 let dates = kind.descriptor().fields.iter().filter_map(|field| {
136 let text = values.text(field.key).filter(|text| !text.is_empty())?;
137 matches!(field.kind, Kind::Date { .. }).then(|| format!("{}={text}", field.key))
138 });
139 std::iter::once(kind.label().to_string())
140 .chain(dates)
141 .collect::<Vec<_>>()
142 .join(" ")
143 }
144
145 #[must_use]
146 pub fn table_loaded(&self) -> bool {
147 matches!(self.state, Fetch::Loaded(_))
148 }
149
150 #[must_use]
152 pub fn chart_visible(&self) -> bool {
153 self.chart.shown() && self.table_loaded()
154 }
155
156 pub fn draw(&self, buf: &mut Buffer, area: Rect, ctx: &mut DrawCtx) {
158 Chrome::new(ctx.theme, &ctx.title, ctx.frame).render(area, buf);
159 if self.chart_visible() {
160 return self.chart.draw(buf, inner(area), ctx);
161 }
162 let text = match &self.state {
163 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 Fetch::Loading { .. } => "Loading...".to_string(),
165 Fetch::Error(e) => format!("[error] {e}"),
166 Fetch::Loaded(lines) => return self.draw_table(buf, area, lines, ctx),
167 };
168 Paragraph::new(text).render(inner(area), buf);
169 }
170
171 fn draw_table(&self, buf: &mut Buffer, area: Rect, lines: &[String], ctx: &mut DrawCtx) {
172 let rows = lines.len();
173 let view = usize::from(Panel::inner(area).height);
174 let top = self.scroll.fit(rows, view);
175 let scroll = u16::try_from(top).unwrap_or(u16::MAX);
176 let table = Paragraph::new(lines.join("\n")).scroll((scroll, 0));
177 table.render(inner(area), buf);
178 let shown = top..(top + view).min(rows);
179 if let Some(info) = range_text(shown, rows).filter(|_| rows > view) {
180 render_info(ctx.theme, area, buf, ctx.frame, &info);
181 }
182 render_scrollbar(ctx.theme, area, buf, (rows, view, top));
183 ctx.hits
184 .push(Panel::inner(area), Target::Body(Surface::Pane));
185 for (rect, part) in scrollbar_parts(area, (rows, view, top)) {
186 ctx.hits.push(rect, Target::Scroll(Surface::Pane, part));
187 }
188 }
189}
190
191impl Default for ReportsTab {
192 fn default() -> Self {
193 Self::new()
194 }
195}
196
197fn parse_report_reply(wire: &str, kind: ReportKind) -> Fetch<Vec<String>> {
199 match parse_wire(wire) {
200 Err(e) => Fetch::Error(e.to_string()),
201 Ok(WireValue::Value(value)) => match build_table(&value, kind) {
202 Ok(lines) => Fetch::Loaded(lines),
203 Err(e) => Fetch::Error(e.to_string()),
204 },
205 }
206}
207
208fn build_table(
209 value: &scripting::nomiscript::Value,
210 kind: ReportKind,
211) -> Result<Vec<String>, CommandError> {
212 Ok(match kind {
213 ReportKind::Balance => balance_table(&value_to_balance_rows(value)?),
214 ReportKind::Activity => activity_table(&value_to_activity_periods(value)?),
215 ReportKind::Breakdown => breakdown_table(&value_to_breakdown_periods(value)?),
216 })
217}
218
219pub mod chart;
220pub(crate) mod table;
221
222#[cfg(test)]
223mod tests;
224
225#[cfg(test)]
226mod table_tests;