Open the report on last month

The report answered for the whole index, which is the one window a spending
report is least often asked for: last January's groceries sat in the same total
as last week's, and nothing on screen said which was which. It now opens on the
month that has just ended -- the last one a statement can be complete for --
and left/right step along an axis beside the totals, from all time down through
the named windows to the oldest month the index holds.

The period narrows the report and nothing else. reloadReport runs its own query
rather than reusing the rows the transaction list is showing: the two share the
account, the search and the untagged toggle, and differ only in the date
bounds, so opening on last month must not hide the rest of the index from the
list beside it. Nothing may put the period into m.filter, which is exactly what
would make it leak.

The windows are relative to today, never to the newest statement. "Last month"
with nothing in it reports nothing and says so, because silently answering for
a month nobody asked for is worse than an empty screen; an empty period and an
empty index therefore give different messages, one asking for another period
and the other for an import. The rolling windows run to the end of this month
rather than to the last complete one -- "last 3 months" is asked in order to
see what is happening now, and leaving out the days since the 1st answers a
question nobody put. The axis is built over the whole index rather than the
rows in view, or it would grow and shrink as the account or search filter
changed and move under the cursor; a reload rebuilds it, since an import can
reach further back, but keeps the window the user was on.

s cycles how those rows are arranged: largest out first as before, then in, net
lowest first so the biggest losses lead, count, and the tag A to Z. A letter
rather than a chord because the report is not a form. The marked heading says
which column the rows are read from and the help names what the key does next,
as the rule builder's preview already does. The sort rearranges rows and never
changes which rows there are, so the order stays out of the filter for the same
reason the period does. Currency remains the outer key under every order --
there are no rates here, so two currencies interleaved by amount would invite a
comparison that cannot be made -- and every order falls back to the tag, so
ties keep a fixed position instead of reshuffling between reloads.

money report takes the same choice as --sort out|in|net|count|tag, and a
misspelt one is refused rather than silently reporting in the default order. It
keeps --month and has no equivalent of the wider windows.

store.Filter gains From and To, compared as strings because dates are stored
ISO-8601 and a string comparison is therefore a date comparison. store.Months
replaces report.Months, which nothing had ever called: the axis needs the
months of the whole index, not of a slice already in hand.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-23 15:45:23 +02:00
co-authored by Claude Opus 5
parent 656e7e1de4
commit 7d4c3eba17
10 changed files with 1236 additions and 45 deletions
+235 -15
View File
@@ -8,6 +8,7 @@ import (
"sort"
"strconv"
"strings"
"time"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/table"
@@ -163,6 +164,19 @@ type Model struct {
filter store.Filter
onlyUntagged bool
// The report's time axis: the windows ←/→ steps along, and which one it is
// on. It is built from the whole index rather than from the rows on screen,
// so changing account or search does not move the axis under the cursor.
reportPeriods []report.Period
reportPeriod int
// reportOrder is how the breakdown is arranged. It is not part of the
// filter: it changes the order of the rows, never which rows there are.
reportOrder report.Order
// indexEmpty is whether the index holds no transactions at all, which the
// report's empty state has to tell apart from a period that happens to be
// empty: one asks for an import, the other for another period.
indexEmpty bool
status string
err error
width int
@@ -192,6 +206,12 @@ var (
hintStyle = lipgloss.NewStyle().Faint(true).PaddingLeft(2)
matchCountStyle = lipgloss.NewStyle().Bold(true).PaddingLeft(2)
ruleFormStyle = lipgloss.NewStyle().Width(ruleFormWidth)
// The report's time axis. The header is bold and indented like the table's
// own header beside it, so the two panels read as one grid.
periodHeaderStyle = lipgloss.NewStyle().Bold(true).PaddingLeft(2).Width(periodListWidth)
periodStyle = lipgloss.NewStyle().Faint(true).Width(periodListWidth)
periodSelectedStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("62")).Width(periodListWidth)
)
// Run starts the interface.
@@ -244,7 +264,7 @@ func New(root string, db *store.DB, accounts []*config.Account, engine *rules.En
table.WithHeight(15), table.WithStyles(styles))
}
return &Model{
m := &Model{
root: root,
db: db,
accounts: accounts,
@@ -308,15 +328,49 @@ func New(root string, db *store.DB, accounts []*config.Account, engine *rules.En
{Title: "Tol", Width: 6},
{Title: "Note", Width: 20},
}),
reportTable: newTable([]table.Column{
{Title: "Tag", Width: 20},
{Title: "Cur", Width: 4},
{Title: "Out", Width: 14},
{Title: "In", Width: 14},
{Title: "Net", Width: 14},
{Title: "N", Width: 5},
}),
reportTable: newTable(slices.Clone(reportColumns)),
}
// The default order needs its marker as much as a chosen one does.
m.markSortedColumn()
return m
}
// reportColumns are the report's headings before the sort marker is added.
// They live here rather than being written into the table once, because
// markSortedColumn rebuilds them every time the order changes.
var reportColumns = []table.Column{
{Title: "Tag", Width: 20},
{Title: "Cur", Width: 4},
{Title: "Out", Width: 14},
{Title: "In", Width: 14},
{Title: "Net", Width: 14},
{Title: "N", Width: 5},
}
// markSortedColumn moves the marker onto the heading the rows are ordered by,
// so the sort is visible where it is acting rather than only in the key list.
func (m *Model) markSortedColumn() {
marker := " ▾"
if m.reportOrder.Ascending() {
marker = " ▴"
}
cols := slices.Clone(reportColumns)
for i := range cols {
if cols[i].Title == m.reportOrder.Column() {
cols[i].Title += marker
break
}
}
m.reportTable.SetColumns(cols)
}
// setOrder cycles the report to the next arrangement of the same rows.
func (m *Model) setOrder(o report.Order) {
m.reportOrder = o
m.markSortedColumn()
m.status = "sort: " + o.Label()
m.reportTable.SetCursor(0)
m.err = m.reloadReport()
}
// Init implements tea.Model.
@@ -327,9 +381,59 @@ func (m *Model) reload() error {
if err := m.reloadAccounts(); err != nil {
return err
}
if err := m.reloadPeriods(); err != nil {
return err
}
return m.reloadTxns()
}
// reloadPeriods rebuilds the report's time axis from the months the index now
// holds, staying on the window the user was looking at if it is still there.
// An import that reaches further back grows the axis, so it cannot simply be
// built once at startup; but it must not throw the user back to the default
// either, since the import they just ran is usually the reason they are looking.
func (m *Model) reloadPeriods() error {
months, err := m.db.Months()
if err != nil {
return err
}
var was string
if p, ok := m.currentPeriod(); ok {
was = p.Label
}
m.indexEmpty = len(months) == 0
m.reportPeriods = report.Periods(time.Now(), months)
m.reportPeriod = report.DefaultIndex(m.reportPeriods)
for i, p := range m.reportPeriods {
if p.Label == was {
m.reportPeriod = i
break
}
}
return nil
}
// currentPeriod is the window the report is on, if the axis has been built.
func (m *Model) currentPeriod() (report.Period, bool) {
if m.reportPeriod < 0 || m.reportPeriod >= len(m.reportPeriods) {
return report.Period{}, false
}
return m.reportPeriods[m.reportPeriod], true
}
// setPeriod moves the report along its axis, clamping at both ends: the axis
// runs from all time down to the oldest month, and wrapping round from one to
// the other would land somewhere nobody aimed for.
func (m *Model) setPeriod(i int) {
if i < 0 || i >= len(m.reportPeriods) || i == m.reportPeriod {
return
}
m.reportPeriod = i
m.status = "period: " + m.reportPeriods[i].String()
m.reportTable.SetCursor(0)
m.err = m.reloadReport()
}
func (m *Model) reloadAccounts() error {
accounts, err := m.db.Accounts()
if err != nil {
@@ -380,8 +484,7 @@ func (m *Model) reloadTxns() error {
}
m.txnTable.SetCursor(cursor)
m.reloadReport(txns)
return nil
return m.reloadReport()
}
// The two rows the report grows below TOTAL. They are bracketed like
@@ -393,8 +496,25 @@ const (
feesRow = " ⤷ fees"
)
func (m *Model) reloadReport(txns []model.Transaction) {
rows := report.ByTag(txns)
// reloadReport re-queries under the report's own time window.
//
// It cannot reuse the rows the transaction list is showing: the period narrows
// the report and only the report, so that opening on last month does not also
// hide the rest of the index from the list beside it. Everything else about the
// scope — the account, the search, the untagged toggle — is shared, so the two
// screens still answer for the same selection of transactions.
func (m *Model) reloadReport() error {
f := m.filter
f.Untagged = m.onlyUntagged
if p, ok := m.currentPeriod(); ok {
f.From, f.To = p.From, p.To
}
txns, err := m.db.Transactions(f)
if err != nil {
return err
}
rows := report.ByTag(txns, m.reportOrder)
out := make([]table.Row, 0, len(rows)+2)
for _, r := range rows {
out = append(out, table.Row{
@@ -435,6 +555,7 @@ func (m *Model) reloadReport(txns []model.Transaction) {
}
}
m.reportTable.SetRows(out)
return nil
}
// ruleFormWidth is the width of the rule builder's left-hand form, and
@@ -1862,6 +1983,27 @@ func (m *Model) updateNormal(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
case "7":
m.openTransferList()
return m, nil
case "s":
// Re-sorting only means anything where there is a breakdown to sort.
if m.view != viewReport {
break
}
m.setOrder(m.reportOrder.Next())
return m, nil
case "left", "right":
// The report's time axis. Every other view leaves these to its table,
// which is what breaking out of the switch here does.
if m.view != viewReport {
break
}
step := 1
if msg.String() == "left" {
step = -1
}
m.setPeriod(m.reportPeriod + step)
return m, nil
case "tab":
m.view = (m.view + 1) % viewCount
switch m.view {
@@ -1984,7 +2126,7 @@ func (m *Model) View() string {
case viewTxns:
b.WriteString(m.txnTable.View())
case viewReport:
b.WriteString(m.reportTable.View())
b.WriteString(m.reportView())
case viewRules:
b.WriteString(m.rulesView())
case viewRuleList:
@@ -2019,6 +2161,72 @@ func (m *Model) View() string {
return b.String()
}
// periodListWidth is the width of the report's time axis, wide enough for the
// longest window name plus its cursor.
const periodListWidth = 18
// reportView puts the time axis to the left of the totals, so the window the
// numbers are for is visible without reading the title and ←/→ has something to
// point at. On a window too narrow for both, the totals win and the axis is
// dropped: the title still names the period, and truncated money columns would
// be worse than a hidden list of periods.
func (m *Model) reportView() string {
axis := m.periodList()
if axis == "" {
return m.reportTable.View()
}
return lipgloss.JoinHorizontal(lipgloss.Top, axis, m.reportTable.View())
}
// periodList renders the axis, scrolled to keep the selected window on screen.
// Its header stands in for the table's own, which is a single unruled line, so
// the two panels line up row for row without a separator of their own.
func (m *Model) periodList() string {
if len(m.reportPeriods) == 0 {
return ""
}
if m.width > 0 && m.width < tableWidth(m.reportTable)+periodListWidth {
return ""
}
h := m.reportTable.Height()
if h <= 0 || h > len(m.reportPeriods) {
h = len(m.reportPeriods)
}
// Centre the cursor where there is room, so the windows either side of the
// one being read are visible and stepping has somewhere obvious to go.
start := m.reportPeriod - h/2
if start > len(m.reportPeriods)-h {
start = len(m.reportPeriods) - h
}
if start < 0 {
start = 0
}
var b strings.Builder
b.WriteString(periodHeaderStyle.Render("Period"))
for i := start; i < start+h; i++ {
line := " " + m.reportPeriods[i].Label
style := periodStyle
if i == m.reportPeriod {
line = "▸ " + m.reportPeriods[i].Label
style = periodSelectedStyle
}
b.WriteString("\n" + style.Render(line))
}
return b.String()
}
// tableWidth is how many cells a table renders across, the cell style's padding
// on either side of every column included.
func tableWidth(t table.Model) int {
w := 0
for _, c := range t.Columns() {
w += c.Width + 2
}
return w
}
// rulesView puts the form on the left and the live preview on the right.
func (m *Model) rulesView() string {
return lipgloss.JoinHorizontal(lipgloss.Top, m.ruleFormView(), m.ruleTable.View())
@@ -2150,6 +2358,12 @@ func (m *Model) emptyMessage() string {
if len(m.reportTable.Rows()) > 0 {
return ""
}
// A period with nothing in it is not the same as an empty index, and
// saying so matters most in the default window: statements for the month
// that has just ended often have not been downloaded yet.
if p, ok := m.currentPeriod(); ok && p.From != "" && !m.indexEmpty {
return fmt.Sprintf("Nothing in %s.\n\nPress ←/→ for another period, or i to import.", p.String())
}
return "Nothing to report yet.\n\nPress i to import some statements first."
case viewRuleList:
@@ -2205,6 +2419,9 @@ func (m *Model) title() string {
}
return fmt.Sprintf("money · transfers · %d definitions · every leg paired", n)
case viewReport:
if p, ok := m.currentPeriod(); ok {
return "money · report · " + p.String() + " · " + scope
}
return "money · report · " + scope
default:
return fmt.Sprintf("money · transactions · %s · %d rows", scope, len(m.txns))
@@ -2256,7 +2473,10 @@ func (m *Model) help() string {
}
return "d delete transfer · p prune all unmatched · r refresh pairing · 6 new transfer · 5 rules · 1 accounts · esc back · q quit"
case viewReport:
return "1 accounts · 2 transactions · 4 new rule · 5 rules · 7 transfers · u untagged · a all accounts · q quit"
// The key is named by what pressing it does now, not by the order the
// rows are already in.
return "←/→ period · s sort by " + m.reportOrder.Next().String() +
" · 1 accounts · 2 transactions · 4 new rule · 5 rules · 7 transfers · u untagged · a all accounts · q quit"
default:
return "4 new rule · / search · u untagged · a all · i import · r retag · 5 rules · 7 transfers · q quit"
}