Lines
96.55 %
Functions
95 %
Branches
100 %
//! Reports tab: balance / activity / category-breakdown.
//!
//! `ReportsTab` holds the current fetch state and the last successful table.
//! `on_reply` parses a wire frame with the shared `cli_core::reports` helpers
//! and lays the reply's rows out as an exact table (`table`).
use chart::ChartPane;
use cli_core::CommandError;
use cli_core::render::{WireValue, parse_wire};
use cli_core::reports::{
value_to_activity_periods, value_to_balance_rows, value_to_breakdown_periods,
};
use forms::{FormValues, Kind};
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::{Paragraph, Widget};
use tvui::{
Chrome, Panel, RowWindow, inner, range_text, render_info, render_scrollbar, scrollbar_parts,
use crate::event::Intent;
use crate::hits::{Surface, Target};
use crate::scroll;
use crate::tabs::fetch::Fetch;
use crate::tabs::seq::Seq;
use crate::view::DrawCtx;
use table::{activity_table, balance_table, breakdown_table};
/// Which report is currently loaded or being fetched.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReportKind {
Balance,
Activity,
Breakdown,
}
impl ReportKind {
pub const ALL: [Self; 3] = [Self::Balance, Self::Activity, Self::Breakdown];
/// The shared form descriptor that sets this report up.
#[must_use]
pub fn descriptor(self) -> &'static forms::Form {
match self {
ReportKind::Balance => &forms::REPORT_BALANCE,
ReportKind::Activity => &forms::REPORT_ACTIVITY,
ReportKind::Breakdown => &forms::REPORT_CATEGORY,
pub fn label(self) -> &'static str {
ReportKind::Balance => "Balance",
ReportKind::Activity => "Activity",
ReportKind::Breakdown => "Category Breakdown",
pub struct ReportsTab {
pub state: Fetch<Vec<String>>,
/// First table line shown.
pub scroll: RowWindow,
/// Which report produced the current (or pending) fetch.
pub kind: ReportKind,
/// The last accepted report with the exact values it ran with.
last: Option<(ReportKind, FormValues)>,
/// The report the table or loading state belongs to.
shown: Option<(ReportKind, FormValues)>,
pub chart: ChartPane,
pub run_seq: Seq,
pub csv_seq: Seq,
impl ReportsTab {
pub fn new() -> Self {
Self {
state: Fetch::Idle,
scroll: RowWindow::default(),
kind: ReportKind::Balance,
last: None,
shown: None,
chart: ChartPane::new(),
run_seq: Seq::default(),
csv_seq: Seq::default(),
/// Scroll by the intent's step; other intents are not scrolling.
pub fn scroll_by(&self, intent: Intent) -> bool {
scroll::apply(&self.scroll, intent)
/// Set loading state once an eval id is assigned.
pub fn set_loading(&mut self, id: i64, kind: ReportKind, values: &FormValues) {
self.kind = kind;
self.shown = Some((kind, values.clone()));
self.scroll.reset();
self.state = Fetch::Loading { id };
/// Apply a routed reply, parsing it with the `kind` that produced the
/// request (carried on the route), not the tab's current selection — the
/// two can differ if a newer request was issued before this reply.
/// Only an accepted reply makes `values` the report to re-run and re-edit.
pub fn on_reply(&mut self, wire: &str, kind: ReportKind, values: FormValues) {
self.state = parse_report_reply(wire, kind);
if !matches!(self.state, Fetch::Error(_)) {
self.shown = Some((kind, values));
self.last.clone_from(&self.shown);
/// Drop the loading state of a run that a newer one superseded.
pub fn abandon_loading(&mut self) {
if matches!(self.state, Fetch::Loading { .. }) {
self.state = Fetch::Idle;
pub fn last(&self) -> Option<&(ReportKind, FormValues)> {
self.last.as_ref()
/// The shown report's label and its date values, e.g. `Activity from=2026-01-01`.
pub fn title(&self) -> String {
let Some((kind, values)) = &self.shown else {
return self.kind.label().to_string();
let dates = kind.descriptor().fields.iter().filter_map(|field| {
let text = values.text(field.key).filter(|text| !text.is_empty())?;
matches!(field.kind, Kind::Date { .. }).then(|| format!("{}={text}", field.key))
});
std::iter::once(kind.label().to_string())
.chain(dates)
.collect::<Vec<_>>()
.join(" ")
pub fn table_loaded(&self) -> bool {
matches!(self.state, Fetch::Loaded(_))
/// Whether the chart replaces the table: only over a table that is loaded.
pub fn chart_visible(&self) -> bool {
self.chart.shown() && self.table_loaded()
/// Render the tab into `area`.
pub fn draw(&self, buf: &mut Buffer, area: Rect, ctx: &mut DrawCtx) {
Chrome::new(ctx.theme, &ctx.title, ctx.frame).render(area, buf);
if self.chart_visible() {
return self.chart.draw(buf, inner(area), ctx);
let text = match &self.state {
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(),
Fetch::Loading { .. } => "Loading...".to_string(),
Fetch::Error(e) => format!("[error] {e}"),
Fetch::Loaded(lines) => return self.draw_table(buf, area, lines, ctx),
Paragraph::new(text).render(inner(area), buf);
fn draw_table(&self, buf: &mut Buffer, area: Rect, lines: &[String], ctx: &mut DrawCtx) {
let rows = lines.len();
let view = usize::from(Panel::inner(area).height);
let top = self.scroll.fit(rows, view);
let scroll = u16::try_from(top).unwrap_or(u16::MAX);
let table = Paragraph::new(lines.join("\n")).scroll((scroll, 0));
table.render(inner(area), buf);
let shown = top..(top + view).min(rows);
if let Some(info) = range_text(shown, rows).filter(|_| rows > view) {
render_info(ctx.theme, area, buf, ctx.frame, &info);
render_scrollbar(ctx.theme, area, buf, (rows, view, top));
ctx.hits
.push(Panel::inner(area), Target::Body(Surface::Pane));
for (rect, part) in scrollbar_parts(area, (rows, view, top)) {
ctx.hits.push(rect, Target::Scroll(Surface::Pane, part));
impl Default for ReportsTab {
fn default() -> Self {
Self::new()
/// Parse a wire reply frame into the table lines for the given kind.
fn parse_report_reply(wire: &str, kind: ReportKind) -> Fetch<Vec<String>> {
match parse_wire(wire) {
Err(e) => Fetch::Error(e.to_string()),
Ok(WireValue::Value(value)) => match build_table(&value, kind) {
Ok(lines) => Fetch::Loaded(lines),
},
fn build_table(
value: &scripting::nomiscript::Value,
kind: ReportKind,
) -> Result<Vec<String>, CommandError> {
Ok(match kind {
ReportKind::Balance => balance_table(&value_to_balance_rows(value)?),
ReportKind::Activity => activity_table(&value_to_activity_periods(value)?),
ReportKind::Breakdown => breakdown_table(&value_to_breakdown_periods(value)?),
})
pub mod chart;
pub(crate) mod table;
#[cfg(test)]
mod tests;
mod table_tests;