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:
+235
-15
@@ -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"
|
||||
}
|
||||
|
||||
+398
-1
@@ -69,6 +69,20 @@ func newTestModel(t *testing.T) (*Model, *store.DB) {
|
||||
return m, db
|
||||
}
|
||||
|
||||
// allTime moves the report off its default window. That window is last month,
|
||||
// while the fixtures are dated whenever they were written, so a test that wants
|
||||
// to see every transaction in the report has to say so.
|
||||
func allTime(t *testing.T, m *Model) {
|
||||
t.Helper()
|
||||
m.setPeriod(0)
|
||||
if p, _ := m.currentPeriod(); p.Label != "all time" {
|
||||
t.Fatalf("period = %q, want all time", p.Label)
|
||||
}
|
||||
if m.err != nil {
|
||||
t.Fatal(m.err)
|
||||
}
|
||||
}
|
||||
|
||||
// key sends a single keypress to the model.
|
||||
func key(t *testing.T, m *Model, s string) {
|
||||
t.Helper()
|
||||
@@ -183,6 +197,7 @@ func TestReportViewCoversEveryTransaction(t *testing.T) {
|
||||
m, _ := newTestModel(t)
|
||||
|
||||
key(t, m, "3") // report view
|
||||
allTime(t, m)
|
||||
view := m.View()
|
||||
for _, want := range []string{"groceries", report.Untagged, "TOTAL"} {
|
||||
if !strings.Contains(view, want) {
|
||||
@@ -1131,6 +1146,7 @@ func TestEmptyReportMessage(t *testing.T) {
|
||||
// With data present, the tables render instead of the empty-state text.
|
||||
func TestNoEmptyMessageWhenPopulated(t *testing.T) {
|
||||
m, _ := newTestModel(t)
|
||||
allTime(t, m)
|
||||
for _, k := range []string{"1", "2", "3"} {
|
||||
key(t, m, k)
|
||||
if got := m.emptyMessage(); got != "" {
|
||||
@@ -1316,7 +1332,7 @@ func TestTransferBuilderSavesAndPairs(t *testing.T) {
|
||||
|
||||
// The paired movement is out of the report; the unpaired leg is not.
|
||||
var out int64
|
||||
for _, r := range report.ByTag(txns) {
|
||||
for _, r := range report.ByTag(txns, report.OrderOut) {
|
||||
out += r.Out
|
||||
}
|
||||
if want := int64(52000); out != want {
|
||||
@@ -1799,6 +1815,7 @@ func TestTransferBuilderTolerance(t *testing.T) {
|
||||
}
|
||||
|
||||
// The pair is gone from the report, so the fee it took has to be named.
|
||||
allTime(t, m)
|
||||
var rows []string
|
||||
for _, r := range m.reportTable.Rows() {
|
||||
rows = append(rows, strings.Join(r, " "))
|
||||
@@ -2185,3 +2202,383 @@ func TestRuleBuilderSortsByCount(t *testing.T) {
|
||||
t.Errorf("preview = %v, want %v: the glob still filters, in count order", all, want)
|
||||
}
|
||||
}
|
||||
|
||||
// monthsAgo is the 15th of the month n before this one. Mid-month on purpose:
|
||||
// a fixture on the 31st would land in a different month than intended as soon
|
||||
// as the month before it is shorter.
|
||||
func monthsAgo(n int) time.Time {
|
||||
now := time.Now()
|
||||
return time.Date(now.Year(), now.Month(), 15, 0, 0, 0, 0, time.UTC).AddDate(0, -n, 0)
|
||||
}
|
||||
|
||||
// newDatedModel builds a model whose transactions are dated relative to today:
|
||||
// 10.00 of groceries last month and 25.00 three months back.
|
||||
func newDatedModel(t *testing.T) *Model {
|
||||
t.Helper()
|
||||
|
||||
db, err := store.Open(filepath.Join(t.TempDir(), "index.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
accountID, err := db.UpsertAccount(model.Account{
|
||||
Slug: "checking", Name: "Checking", Currency: "EUR", MinorDigits: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceID, err := db.SourceFile(accountID, "checking/st.csv", "sha", "2026-01-01T00:00:00Z")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
when time.Time
|
||||
desc string
|
||||
amount int64
|
||||
}{
|
||||
{monthsAgo(1), "LIDL SOFIA", -1000},
|
||||
{monthsAgo(3), "LIDL PLOVDIV", -2500},
|
||||
} {
|
||||
if _, err := db.InsertTransaction(model.Transaction{
|
||||
AccountID: accountID,
|
||||
SourceFileID: sourceID,
|
||||
Fingerprint: tc.desc,
|
||||
Date: tc.when.Format("2006-01-02"),
|
||||
Description: tc.desc,
|
||||
AmountMinor: tc.amount,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
engine := rules.New(&config.Rules{Rule: []config.Rule{{Match: "*LIDL*", Tag: "groceries"}}})
|
||||
if _, err := engine.Retag(db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
m := New(t.TempDir(), db, nil, engine, transfers.New(&config.Rules{}))
|
||||
if err := m.reload(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Update(tea.WindowSizeMsg{Width: 120, Height: 30})
|
||||
return m
|
||||
}
|
||||
|
||||
// reportOut is what the report says one tag spent, or "" if it has no row.
|
||||
func reportOut(m *Model, tag string) string {
|
||||
for _, r := range m.reportTable.Rows() {
|
||||
if r[0] == tag {
|
||||
return r[2]
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// The report opens on last month, not on everything: an all-time total is the
|
||||
// one number a spending report is least often asked for.
|
||||
func TestReportOpensOnLastMonth(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
|
||||
p, ok := m.currentPeriod()
|
||||
if !ok || p.Label != report.LastMonth {
|
||||
t.Fatalf("period = %+v, want %q", p, report.LastMonth)
|
||||
}
|
||||
if got := reportOut(m, "groceries"); got != "10.00" {
|
||||
t.Errorf("groceries = %q, want only last month's 10.00", got)
|
||||
}
|
||||
key(t, m, "3")
|
||||
if view := m.View(); !strings.Contains(view, "last month") {
|
||||
t.Errorf("title does not name the period:\n%s", view)
|
||||
}
|
||||
}
|
||||
|
||||
// The period narrows the report and only the report. Opening on last month
|
||||
// must not quietly hide the rest of the index from the transaction list.
|
||||
func TestReportPeriodLeavesTheTransactionListAlone(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
|
||||
if len(m.txns) != 2 {
|
||||
t.Fatalf("transaction list has %d rows, want both", len(m.txns))
|
||||
}
|
||||
key(t, m, "3")
|
||||
key(t, m, "right")
|
||||
if len(m.txns) != 2 {
|
||||
t.Errorf("stepping the period changed the transaction list to %d rows", len(m.txns))
|
||||
}
|
||||
if m.filter.From != "" || m.filter.To != "" {
|
||||
t.Errorf("the period leaked into the shared filter: %+v", m.filter)
|
||||
}
|
||||
}
|
||||
|
||||
// →Steps to the next window along, which past last month is the months the
|
||||
// index actually holds.
|
||||
func TestReportPeriodSteps(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
key(t, m, "3")
|
||||
|
||||
key(t, m, "right")
|
||||
want := monthsAgo(3).Format("2006-01")
|
||||
if p, _ := m.currentPeriod(); p.Label != want {
|
||||
t.Fatalf("period = %q, want %q", p.Label, want)
|
||||
}
|
||||
if got := reportOut(m, "groceries"); got != "25.00" {
|
||||
t.Errorf("groceries = %q, want that month's 25.00", got)
|
||||
}
|
||||
|
||||
key(t, m, "left")
|
||||
if p, _ := m.currentPeriod(); p.Label != report.LastMonth {
|
||||
t.Errorf("stepping back landed on %q, want %q", p.Label, report.LastMonth)
|
||||
}
|
||||
}
|
||||
|
||||
// The axis clamps at both ends rather than wrapping: all time and the oldest
|
||||
// month are as far as the two directions go.
|
||||
func TestReportPeriodClampsAtBothEnds(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
key(t, m, "3")
|
||||
|
||||
for range 10 {
|
||||
key(t, m, "left")
|
||||
}
|
||||
if p, _ := m.currentPeriod(); p.Label != "all time" {
|
||||
t.Errorf("period = %q, want all time", p.Label)
|
||||
}
|
||||
if got := reportOut(m, "groceries"); got != "35.00" {
|
||||
t.Errorf("groceries over all time = %q, want 35.00", got)
|
||||
}
|
||||
|
||||
last := len(m.reportPeriods) - 1
|
||||
for range 20 {
|
||||
key(t, m, "right")
|
||||
}
|
||||
if m.reportPeriod != last {
|
||||
t.Errorf("period index = %d, want it to stop at %d", m.reportPeriod, last)
|
||||
}
|
||||
}
|
||||
|
||||
// The axis is on screen beside the totals, so the window the numbers are for
|
||||
// does not have to be read out of the title.
|
||||
func TestReportShowsThePeriodAxis(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
key(t, m, "3")
|
||||
|
||||
view := m.View()
|
||||
for _, want := range []string{"Period", "▸ " + report.LastMonth, "all time", "←/→ period"} {
|
||||
if !strings.Contains(view, want) {
|
||||
t.Errorf("report view is missing %q:\n%s", want, view)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A window with nothing in it is not an empty index, and the two want different
|
||||
// answers: one is fixed by stepping the period, the other by importing.
|
||||
func TestEmptyPeriodIsNotAnEmptyIndex(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
key(t, m, "3")
|
||||
|
||||
// Two months back holds neither fixture.
|
||||
for _, p := range m.reportPeriods {
|
||||
if p.Label == monthsAgo(2).Format("2006-01") {
|
||||
t.Fatalf("did not expect a window for an empty month: %+v", p)
|
||||
}
|
||||
}
|
||||
m.filter.Search = "NOTHING MATCHES THIS"
|
||||
if err := m.reloadReport(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := m.emptyMessage(); !strings.Contains(got, "period") {
|
||||
t.Errorf("empty period message = %q, want it to point at the period", got)
|
||||
}
|
||||
if strings.Contains(m.emptyMessage(), "import some statements") {
|
||||
t.Error("an empty period asked for an import, but the index has statements")
|
||||
}
|
||||
}
|
||||
|
||||
// An import that reaches further back grows the axis without moving the window
|
||||
// the user is reading.
|
||||
func TestPeriodAxisSurvivesAReload(t *testing.T) {
|
||||
m := newDatedModel(t)
|
||||
key(t, m, "3")
|
||||
key(t, m, "right")
|
||||
was, _ := m.currentPeriod()
|
||||
|
||||
if err := m.reload(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := m.currentPeriod(); p.Label != was.Label {
|
||||
t.Errorf("reload moved the period from %q to %q", was.Label, p.Label)
|
||||
}
|
||||
}
|
||||
|
||||
// newSortModel builds a report worth sorting: three tags that come out in a
|
||||
// different order under each arrangement.
|
||||
func newSortModel(t *testing.T) *Model {
|
||||
t.Helper()
|
||||
|
||||
db, err := store.Open(filepath.Join(t.TempDir(), "index.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
accountID, err := db.UpsertAccount(model.Account{
|
||||
Slug: "checking", Name: "Checking", Currency: "EUR", MinorDigits: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceID, err := db.SourceFile(accountID, "checking/st.csv", "sha", "2026-01-01T00:00:00Z")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// One big outflow, three small ones, and an inflow bigger than any of them.
|
||||
rows := []struct {
|
||||
desc string
|
||||
amount int64
|
||||
}{
|
||||
{"RENT", -100000},
|
||||
{"COFFEE 1", -500},
|
||||
{"COFFEE 2", -500},
|
||||
{"COFFEE 3", -500},
|
||||
{"SALARY", 200000},
|
||||
}
|
||||
for _, r := range rows {
|
||||
if _, err := db.InsertTransaction(model.Transaction{
|
||||
AccountID: accountID,
|
||||
SourceFileID: sourceID,
|
||||
Fingerprint: r.desc,
|
||||
Date: monthsAgo(1).Format("2006-01-02"),
|
||||
Description: r.desc,
|
||||
AmountMinor: r.amount,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
engine := rules.New(&config.Rules{Rule: []config.Rule{
|
||||
{Match: "RENT", Tag: "rent"},
|
||||
{Match: "COFFEE*", Tag: "coffee"},
|
||||
{Match: "SALARY", Tag: "salary"},
|
||||
}})
|
||||
if _, err := engine.Retag(db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
m := New(t.TempDir(), db, nil, engine, transfers.New(&config.Rules{}))
|
||||
if err := m.reload(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m.Update(tea.WindowSizeMsg{Width: 120, Height: 30})
|
||||
key(t, m, "3")
|
||||
return m
|
||||
}
|
||||
|
||||
// reportTags is the order the report's tag rows came out in, without the
|
||||
// TOTAL and transfer rows the table grows below them.
|
||||
func reportTags(m *Model) []string {
|
||||
var out []string
|
||||
for _, r := range m.reportTable.Rows() {
|
||||
if r[0] == "TOTAL" || r[0] == transfersRow || r[0] == feesRow {
|
||||
continue
|
||||
}
|
||||
out = append(out, r[0])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// s cycles the arrangement, and every one of them is reachable that way.
|
||||
func TestReportSortCyclesThroughEveryOrder(t *testing.T) {
|
||||
m := newSortModel(t)
|
||||
|
||||
want := map[report.Order][]string{
|
||||
report.OrderOut: {"rent", "coffee", "salary"},
|
||||
report.OrderIn: {"salary", "coffee", "rent"},
|
||||
report.OrderNet: {"rent", "coffee", "salary"},
|
||||
report.OrderCount: {"coffee", "rent", "salary"},
|
||||
report.OrderTag: {"coffee", "rent", "salary"},
|
||||
}
|
||||
if m.reportOrder != report.OrderOut {
|
||||
t.Fatalf("report opened on %s, want %s", m.reportOrder, report.OrderOut)
|
||||
}
|
||||
seen := map[report.Order]bool{}
|
||||
for range len(want) {
|
||||
seen[m.reportOrder] = true
|
||||
if got := reportTags(m); !slices.Equal(got, want[m.reportOrder]) {
|
||||
t.Errorf("%s: rows = %v, want %v", m.reportOrder, got, want[m.reportOrder])
|
||||
}
|
||||
key(t, m, "s")
|
||||
}
|
||||
if len(seen) != len(want) {
|
||||
t.Errorf("cycling reached %d of %d orders", len(seen), len(want))
|
||||
}
|
||||
if m.reportOrder != report.OrderOut {
|
||||
t.Errorf("the cycle ended on %s, want it back where it started", m.reportOrder)
|
||||
}
|
||||
}
|
||||
|
||||
// The sort rearranges the rows and nothing else: the same tags are there, for
|
||||
// the same period, and the transaction list is untouched.
|
||||
func TestReportSortChangesOnlyTheOrder(t *testing.T) {
|
||||
m := newSortModel(t)
|
||||
|
||||
before := slices.Clone(reportTags(m))
|
||||
txns := len(m.txns)
|
||||
period, _ := m.currentPeriod()
|
||||
|
||||
key(t, m, "s")
|
||||
after := slices.Clone(reportTags(m))
|
||||
slices.Sort(before)
|
||||
slices.Sort(after)
|
||||
if !slices.Equal(before, after) {
|
||||
t.Errorf("sorting changed which rows there are: %v then %v", before, after)
|
||||
}
|
||||
if len(m.txns) != txns {
|
||||
t.Errorf("sorting the report changed the transaction list to %d rows", len(m.txns))
|
||||
}
|
||||
if p, _ := m.currentPeriod(); p.Label != period.Label {
|
||||
t.Errorf("sorting moved the period to %q", p.Label)
|
||||
}
|
||||
}
|
||||
|
||||
// The marker sits on the column being sorted, so the order is visible in the
|
||||
// table rather than only in the key list.
|
||||
func TestReportMarksTheSortedColumn(t *testing.T) {
|
||||
m := newSortModel(t)
|
||||
|
||||
for _, want := range []string{"Out ▾", "In ▾", "Net ▾", "N ▾", "Tag ▴"} {
|
||||
view := m.View()
|
||||
if !strings.Contains(view, want) {
|
||||
t.Errorf("%s: header does not mark %q:\n%s", m.reportOrder, want, view)
|
||||
}
|
||||
// Exactly one column carries it, or the header would lie about which
|
||||
// column the rows are arranged by.
|
||||
if n := strings.Count(view, "▾") + strings.Count(view, "▴"); n != 1 {
|
||||
t.Errorf("%s: %d columns marked, want 1", m.reportOrder, n)
|
||||
}
|
||||
key(t, m, "s")
|
||||
}
|
||||
}
|
||||
|
||||
// The key list names what pressing s does next, not the order already in force.
|
||||
func TestReportSortHelpNamesTheNextOrder(t *testing.T) {
|
||||
m := newSortModel(t)
|
||||
if got := m.help(); !strings.Contains(got, "s sort by in") {
|
||||
t.Errorf("help = %q, want it to offer the next order", got)
|
||||
}
|
||||
key(t, m, "s")
|
||||
if got := m.help(); !strings.Contains(got, "s sort by net") {
|
||||
t.Errorf("help = %q, want it to offer the next order", got)
|
||||
}
|
||||
}
|
||||
|
||||
// s belongs to the report. Elsewhere it goes to the table like any other key,
|
||||
// so a view that later wants it is not fighting a global binding.
|
||||
func TestSortKeyIsReportOnly(t *testing.T) {
|
||||
m := newSortModel(t)
|
||||
key(t, m, "2")
|
||||
key(t, m, "s")
|
||||
if m.reportOrder != report.OrderOut {
|
||||
t.Errorf("s re-sorted the report from the transaction list: %s", m.reportOrder)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user