From 239c6021883dd0feb034808e79a16edd4a7e0786 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 10:28:50 -0700 Subject: [PATCH 1/4] Redesign the Reports tab: stat cards, hours by day and CSV export (ALI-2618) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Reports tab now draws from internal/report, the code behind `notch report`, so for the same range its numbers match `notch report -json` (a test compares the two as JSON for every preset). It no longer uses db.ReportByProject, so it reads start dates in local time like the CLI. The screen follows the canvas's Reports board: - Range chips (t Today, w Week, m Month, y Year, a All, f Custom…) with the dates beside them. f opens a Custom range modal (From, To, Apply, Cancel) with field errors; a blank date leaves that side open. - Four stat cards: hours and entries, earned and the average rate, outstanding (invoiced, not paid) and unbilled. - BY DAY: block-character bars in eighth blocks, each with its day and hours written under it; today's bar is in success and its day bold. This week runs on to Sunday. Ranges with more days than fit show a bar per week, month or year. - BY CLIENT AND PROJECT: clients with their projects nested under them, with hours, invoiced and paid counts and earned, and a total. At 120 columns and up the bars sit beside the table; narrower terminals stack them with shorter bars and compact cards, and drop the bars before the table gets fewer than three rows. e exports the range's entries with report.WriteCSV to the XDG download folder (else ~/Downloads, else home), named for the range, adding " (2)", " (3)"… rather than overwriting. The status line shows the path. enter opens the entries behind a client or project row, where e edits an entry as before. New layout tokens: tui-card-gap, tui-bar-width, tui-bar-gap, tui-bar-rows, tui-bar-rows-compact, tui-report-col-hours, tui-report-col-count, tui-report-col-earned, tui-report-trail and tui-report-indent. The keys sheet and README cover the new keys. --- README.md | 59 +- cli_report.go | 4 +- design/build/main.go | 10 + design/tokens.json | 12 +- internal/report/report.go | 6 +- internal/theme/tokens_gen.go | 42 + internal/ui/layout_gen.go | 3 +- internal/ui/render_test.go | 55 ++ internal/ui/views/keys.go | 5 +- internal/ui/views/reports.go | 1176 +++++++++------------------ internal/ui/views/reports_export.go | 181 +++++ internal/ui/views/reports_test.go | 935 +++++++++++++-------- internal/ui/views/reports_view.go | 694 ++++++++++++++++ 13 files changed, 2001 insertions(+), 1181 deletions(-) create mode 100644 internal/ui/views/reports_export.go create mode 100644 internal/ui/views/reports_view.go diff --git a/README.md b/README.md index 7a4b350..d75af87 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ notch delete --project --task "t" # delete every entry of one task, t In `clients -json` and `projects -json`, `monthSeconds` and `monthEarned` are this calendar month's finished time and its value at the client's current rate, clipped to the 1st at local midnight like `summary`'s totals; `unbilled` is every finished entry not yet invoiced, from any date, the same as `summary`'s. All three leave out the running timer, and a client's are its projects' added up, rounded to cents once. `--rate` takes a plain number from 0 to 1,000,000 (`85`, `92.50`; not `$85`). Client names are unique, and so are project names within a client: a clash is an error, not a merge. Names can't be empty or contain tabs or line breaks. `delete` refuses, saying how many entries would go (and whether the running timer is one of them), when a client or project has tracked entries, unless you pass `--yes`; with none it deletes straight away, a client's empty projects included. `-json` on `add` and `edit` prints the result in the list's shape; on `delete`, `{"id":1,"projects":2,"entries":14}`. -`report` covers the entries that started on the range's local dates, like `entries --from/--to`, so a timer that runs past midnight counts on its start day; it leaves out the running timer until it stops. `--range` presets end today (`week` starts on Monday); `all`, or leaving out `--from` or `--to`, opens that side. `-json`'s `outstanding` is the range's invoiced-but-unpaid earnings and `unbilled` its not-yet-invoiced ones (unlike `summary`'s, which cover every date), and `averageRate` is `earned` over the hours. `days` lists every date of the range, 0 for a day with no time; an open side starts or ends at the first or last entry instead, and a span longer than a year lists only the dates from the first entry to the last. Times are in seconds, like the other commands' JSON. The TUI's Reports tab doesn't use this code yet (ALI-2618): it reads start dates in UTC, so near midnight it can put an entry on a different day than `report` does. Money is at each client's current rate, rounded to cents once per row, so a client's `earned` can differ by a cent from adding up its projects'. In `--csv`, `start` and `end` are local date and time (an entry can end the next day), `hours` is rounded to two places, and a cell that a spreadsheet would read as a formula (starting, after any spaces, with `=`, `+`, `-`, `@`, a tab or a carriage return) gets a leading apostrophe, which stays in the text if you import the file elsewhere. +`report` covers the entries that started on the range's local dates, like `entries --from/--to`, so a timer that runs past midnight counts on its start day; it leaves out the running timer until it stops. `--range` presets end today (`week` starts on Monday); `all`, or leaving out `--from` or `--to`, opens that side. `-json`'s `outstanding` is the range's invoiced-but-unpaid earnings and `unbilled` its not-yet-invoiced ones (unlike `summary`'s, which cover every date), and `averageRate` is `earned` over the hours. `days` lists every date of the range, 0 for a day with no time; an open side starts or ends at the first or last entry instead, and a span longer than a year lists only the dates from the first entry to the last. Times are in seconds, like the other commands' JSON. The TUI's Reports tab uses the same code, so for the same range its cards, bars and table show the numbers `report -json` prints. Money is at each client's current rate, rounded to cents once per row, so a client's `earned` can differ by a cent from adding up its projects'. In `--csv`, `start` and `end` are local date and time (an entry can end the next day), `hours` is rounded to two places, and a cell that a spreadsheet would read as a formula (starting, after any spaces, with `=`, `+`, `-`, `@`, a tab or a carriage return) gets a leading apostrophe, which stays in the text if you import the file elsewhere. Without `--task`, `entries` lists every entry whose local start date falls in `--from`…`--to` (either side optional; neither means all time), like the TUI's Timers list, so a late-night timer counts on the day it started; `--query` keeps tasks containing the text, ignoring case. `earned` is the entry's time at its client's current hourly rate, rounded to cents, and counts the running entry's time so far, which `summary`'s totals leave out (add it yourself, as with the seconds). `summary` counts finished entries only, clipped to local day and week boundaries, so a status bar can add the running entry's elapsed time itself and tick locally (clipping it to local midnight and to Monday if it started before them). Its `earnedToday` and `earnedWeek` are clipped the same way; `unbilled` is every finished entry not yet invoiced and `outstanding` every one invoiced but not paid, from any date (the TUI's Reports card "Outstanding" is both together). Totals are rounded to cents once, so show these rather than adding up each entry's `earned`, which can differ by a cent. The plain-text `summary` is unchanged. `edit --start/--end` take RFC3339 or local `YYYY-MM-DD HH:MM`, with the same rules as the TUI's edit form (the end can't be before the start), and neither can be in the future; `--notes ""` clears notes. A whole-task `edit` renames and/or moves the task, merging it into an existing one if the result matches. `--invoiced` and `--paid` take `=true` or `=false` (write the `=`: `--invoiced false` is rejected) and follow the TUI's rules: an entry is paid only once it's invoiced, so `--paid` on an uninvoiced entry fails unless you pass `--invoiced` too; `--invoiced=false` also clears paid; and a running timer can't be invoiced or paid unless the same edit gives it an `--end`. A rejected edit changes nothing, on one entry or a whole task. The one exception is a timer that another process starts in the task mid-edit, which can leave behind a client or project created by `--client-name` or `--project-name`. A whole-task `edit -json` lists every entry of the resulting task, including any it merged into. `delete` doesn't prompt: callers confirm first. Edits and deletes that match nothing exit non-zero. @@ -262,24 +262,24 @@ Clients are created and managed on the Clients tab (press **3**). ### Reports tab -| Key | Action | -| --------- | ------------------------ | -| `↑` / `k` | Move cursor up | -| `↓` / `j` | Move cursor down | -| `f` | Open date filter | -| `t` | Quick filter: Today | -| `w` | Quick filter: This week | -| `m` | Quick filter: This month | -| `y` | Quick filter: This year | -| `a` | Show all time | - -### Reports date filter - -| Key | Action | -| ------------------- | ------------------------------- | -| `tab` / `shift+tab` | Switch between From / To fields | -| `enter` | Apply filter | -| `esc` | Cancel | +| Key | Action | +| --------------------------- | ------------------------------------------------------------ | +| `↑` / `k` | Move cursor up | +| `↓` / `j` | Move cursor down | +| `t` / `w` / `m` / `y` / `a` | Range: today, this week, this month, this year, all time | +| `f` | Range: custom dates (opens a form; blank leaves a side open) | +| `e` | Export the range's entries as CSV to your downloads folder | +| `enter` | Show the entries behind the selected client or project | + +In the entries list, `e` edits the selected entry and `esc` goes back. + +### Reports custom range + +| Key | Action | +| ------------------- | ------------------------------------- | +| `tab` / `shift+tab` | Move between From, To and the buttons | +| `enter` | Apply | +| `esc` | Cancel | --- @@ -300,20 +300,13 @@ The TUI, the CLI, `notch watch` and the bar panel can all have the database open ## Reports -The Reports tab groups all time entries by **Client → Project** and shows: - -- **Hours** — total tracked hours -- **Entries** — number of time entries -- **Invoiced** — how many entries are marked invoiced -- **Paid** — how many entries are marked paid -- **Earned** — hours × client hourly rate +The Reports tab covers the finished entries that started in the chosen range (this month when it opens), with the same code as `notch report`, so the numbers match `notch report -json` for the same range. The running timer counts once it stops. It shows: -Summary cards at the bottom show totals for the selected period: +- **Stat cards** — the range's hours and entries, what they earned (and the average rate), what's outstanding (invoiced, not paid) and what's unbilled (not invoiced yet) +- **By day** — hours as bars, each with its hours written under it; a range with more days than fit shows a bar per week, month or year instead +- **By client and project** — each client, with its projects under it: hours, how many entries are invoiced and paid, and earned (hours × the client's current rate) -- Total Hours -- Total Earned -- Outstanding (earned but not fully paid) -- Uninvoiced entries count +`e` exports the range's entries as CSV, the same rows as `notch report --csv`, to your downloads folder (`XDG_DOWNLOAD_DIR`, else `~/Downloads`, else your home folder). The file is named for the range, such as `notch-2026-11-30-to-2026-12-03.csv`; if that name is taken, the export gets ` (2)`, ` (3)` and so on, so it never overwrites a file. The status line shows where it went. --- @@ -348,7 +341,9 @@ notch/ ├── timers_view.go # Timers list screen: hero, range chips, day groups, detail pane ├── projects.go # Projects tab — flat project list w/ client picker ├── clients.go # Clients tab — client CRUD with billing rate - └── reports.go # Reports tab — date-filtered summary + cards + ├── reports.go # Reports tab — ranges, custom range form, entries behind a row + ├── reports_view.go # Reports screen: range chips, stat cards, hours bars, client table + └── reports_export.go # Reports CSV export to the downloads folder ``` --- diff --git a/cli_report.go b/cli_report.go index 59cf042..edfa0e3 100644 --- a/cli_report.go +++ b/cli_report.go @@ -2,8 +2,8 @@ package main // The "report" command (ALI-2613): a date range's totals, hours by day and // rows by client and project, for scripts and the bar panel. -// internal/report does the work, which the TUI's Reports tab and CSV -// export are to use too (ALI-2618). +// internal/report does the work, which the TUI's Reports tab and its CSV +// export use too (ALI-2618). import ( "flag" diff --git a/design/build/main.go b/design/build/main.go index ecb9071..62c0032 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -347,6 +347,16 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-modal-min-width", "ModalMinWidth"}, {"tui-strip-min", "StripMin"}, {"tui-field-width", "FieldWidth"}, + {"tui-card-gap", "CardGap"}, + {"tui-bar-width", "BarWidth"}, + {"tui-bar-gap", "BarGap"}, + {"tui-bar-rows", "BarRows"}, + {"tui-bar-rows-compact", "BarRowsCompact"}, + {"tui-report-col-hours", "ReportColHours"}, + {"tui-report-col-count", "ReportColCount"}, + {"tui-report-col-earned", "ReportColEarned"}, + {"tui-report-trail", "ReportTrail"}, + {"tui-report-indent", "ReportIndent"}, } { v, err := integer(t.Spacing, c.token) if err != nil { diff --git a/design/tokens.json b/design/tokens.json index e553170..fd80ad8 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -89,7 +89,17 @@ { "name": "tui-modal-min-width", "value": 20, "usage": "TUI: the narrowest a modal gets, border included, however narrow the body is." }, { "name": "tui-strip-min", "value": 8, "usage": "TUI: the narrowest a form field's bg_alt strip gets in a modal." }, { "name": "tui-field-width", "value": 44, "usage": "TUI: a form field's width when the form opens; the modal sets it to its strip's width each time it draws." }, - { "name": "tui-min-width", "value": 64, "usage": "TUI: the narrowest terminal notch draws, in cells, measured from the views: the widest fixed line is the Projects tab's at 57 cells, 61 with the two margins; the compact Timers range chips need 48. Narrower terminals get a centred \"Terminal too small\" message." }, + { "name": "tui-card-gap", "value": 2, "usage": "TUI: blank columns between the Reports tab's four stat cards (hours, earned, outstanding, unbilled), which share the rest of the width." }, + { "name": "tui-bar-width", "value": 5, "usage": "TUI: a Reports hours bar's width, in cells. Crowded ranges get narrower bars, never narrower than their labels." }, + { "name": "tui-bar-gap", "value": 4, "usage": "TUI: blank columns between Reports hours bars; crowded ranges close it to one." }, + { "name": "tui-bar-rows", "value": 5, "usage": "TUI: the Reports hours bars' height in the wide layout, in rows of eighth blocks." }, + { "name": "tui-bar-rows-compact", "value": 3, "usage": "TUI: the Reports hours bars' height in the compact layout (under tui-wide columns, or short terminals), so the client table keeps its rows." }, + { "name": "tui-report-col-hours", "value": 10, "usage": "TUI: the Reports table's HOURS column, right-aligned, room for 1000:00:00 and a gap." }, + { "name": "tui-report-col-count", "value": 10, "usage": "TUI: the Reports table's INVOICED and PAID columns, each right-aligned." }, + { "name": "tui-report-col-earned", "value": 13, "usage": "TUI: the Reports table's EARNED column, right-aligned, room for $100,000.00 and a gap." }, + { "name": "tui-report-trail", "value": 2, "usage": "TUI: blank columns after the Reports table's EARNED column." }, + { "name": "tui-report-indent", "value": 2, "usage": "TUI: how far a project's name sits in from its client's in the Reports table." }, + { "name": "tui-min-width", "value": 64, "usage": "TUI: the narrowest terminal notch draws, in cells, measured from the views: the widest fixed line is the Projects tab's at 57 cells, 61 with the two margins; the compact Timers range chips need 48, and the Reports range chips 58. Narrower terminals get a centred \"Terminal too small\" message." }, { "name": "tui-min-height", "value": 22, "usage": "TUI: the shortest terminal notch draws, in rows: the chrome (4), the body's top and bottom padding (2), the compact Timers screen's fixed rows (14) and two list rows (a day header and the selected entry). A wide terminal this short gets the compact layout, since the wide one needs 23 rows (see tui-wide). Shorter terminals get a centred \"Terminal too small\" message." }, { "name": "tui-chrome-rows", "value": 4, "usage": "TUI: rows taken by the chrome: the tab bar and its rule at the top, and a rule and the hotkey and status line at the bottom (measured from their real output). Content gets the rest." }, { "name": "panel-padding", "value": "14px", "usage": "Bar panel: inner padding, from aliasOS's KeyboardPanel." } diff --git a/internal/report/report.go b/internal/report/report.go index a00fce0..511122c 100644 --- a/internal/report/report.go +++ b/internal/report/report.go @@ -1,10 +1,8 @@ // Package report builds notch's time and money report for a date range: // the totals, hours by day, and rows by client and project that the // redesigned TUI Reports tab and the bar panel show, and the per-entry CSV -// both export. "notch report" prints it. The TUI's Reports tab (ALI-2618) -// and the panel (ALI-2622) are to switch to this package; until then the -// TUI's tab still uses db.ReportByProject, which reads start dates in UTC, -// so near midnight the two can put an entry on different days. +// both export. "notch report" prints it, and the TUI's Reports tab +// (ALI-2618) draws from it; the panel (ALI-2622) is to switch to it too. package report import ( diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index 7ab5770..82e5954 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -193,3 +193,45 @@ const StripMin = 8 // FieldWidth (tui-field-width). TUI: a form field's width when the form // opens; the modal sets it to its strip's width each time it draws. const FieldWidth = 44 + +// CardGap (tui-card-gap). TUI: blank columns between the Reports tab's four +// stat cards (hours, earned, outstanding, unbilled), which share the rest of +// the width. +const CardGap = 2 + +// BarWidth (tui-bar-width). TUI: a Reports hours bar's width, in cells. +// Crowded ranges get narrower bars, never narrower than their labels. +const BarWidth = 5 + +// BarGap (tui-bar-gap). TUI: blank columns between Reports hours bars; +// crowded ranges close it to one. +const BarGap = 4 + +// BarRows (tui-bar-rows). TUI: the Reports hours bars' height in the wide +// layout, in rows of eighth blocks. +const BarRows = 5 + +// BarRowsCompact (tui-bar-rows-compact). TUI: the Reports hours bars' height +// in the compact layout (under tui-wide columns, or short terminals), so the +// client table keeps its rows. +const BarRowsCompact = 3 + +// ReportColHours (tui-report-col-hours). TUI: the Reports table's HOURS +// column, right-aligned, room for 1000:00:00 and a gap. +const ReportColHours = 10 + +// ReportColCount (tui-report-col-count). TUI: the Reports table's INVOICED +// and PAID columns, each right-aligned. +const ReportColCount = 10 + +// ReportColEarned (tui-report-col-earned). TUI: the Reports table's EARNED +// column, right-aligned, room for $100,000.00 and a gap. +const ReportColEarned = 13 + +// ReportTrail (tui-report-trail). TUI: blank columns after the Reports +// table's EARNED column. +const ReportTrail = 2 + +// ReportIndent (tui-report-indent). TUI: how far a project's name sits in +// from its client's in the Reports table. +const ReportIndent = 2 diff --git a/internal/ui/layout_gen.go b/internal/ui/layout_gen.go index 702f4f6..52c16cd 100644 --- a/internal/ui/layout_gen.go +++ b/internal/ui/layout_gen.go @@ -14,7 +14,8 @@ const ChromeRows = 4 // MinWidth (tui-min-width). TUI: the narrowest terminal notch draws, in // cells, measured from the views: the widest fixed line is the Projects tab's // at 57 cells, 61 with the two margins; the compact Timers range chips need -// 48. Narrower terminals get a centred "Terminal too small" message. +// 48, and the Reports range chips 58. Narrower terminals get a centred +// "Terminal too small" message. const MinWidth = 64 // MinHeight (tui-min-height). TUI: the shortest terminal notch draws, in diff --git a/internal/ui/render_test.go b/internal/ui/render_test.go index 78a816a..b491291 100644 --- a/internal/ui/render_test.go +++ b/internal/ui/render_test.go @@ -118,3 +118,58 @@ func TestRenderSample(t *testing.T) { } } } + +// TestRenderReportsSample checks the Reports tab fills the terminal +// exactly at the board's two sizes, with the custom range modal open too, +// and writes plain-text renders to $NOTCH_RENDER_DIR, when set. +func TestRenderReportsSample(t *testing.T) { + for _, size := range [][2]int{{140, 40}, {90, 32}} { + w, h := size[0], size[1] + m := sampleApp(t, w, h) + u, cmd := m.Update(runeKey('4')) + m = u.(AppModel) + u, _ = m.Update(cmd()) + m = u.(AppModel) + u, cmd = m.Update(runeKey('w')) + m = u.(AppModel) + u, _ = m.Update(cmd()) + m = u.(AppModel) + for _, state := range []string{"report", "custom"} { + if state == "custom" { + u, _ = m.Update(runeKey('f')) + m = u.(AppModel) + if !m.activeViewBusy() { + t.Fatalf("%d×%d: the custom range modal should capture keys", w, h) + } + // q types in it rather than quitting. + if _, cmd := m.Update(runeKey('q')); cmd != nil { + if _, quit := cmd().(tea.QuitMsg); quit { + t.Errorf("%d×%d: q quit from the custom range modal", w, h) + } + } + } + out := m.View() + lines := strings.Split(out, "\n") + if len(lines) != h { + t.Errorf("%d×%d %s: %d lines, want %d", w, h, state, len(lines), h) + } + for i, l := range lines { + if lw := lipgloss.Width(l); lw != w { + t.Errorf("%d×%d %s: line %d is %d wide: %q", w, h, state, i, lw, plainText(l)) + } + } + plain := plainText(out) + for _, want := range []string{"BY DAY", "BY CLIENT AND PROJECT", "HOURS", "UNBILLED"} { + if state == "report" && !strings.Contains(plain, want) { + t.Errorf("%d×%d: missing %q:\n%s", w, h, want, plain) + } + } + if dir := os.Getenv("NOTCH_RENDER_DIR"); dir != "" { + name := filepath.Join(dir, fmt.Sprintf("ali-2618-%s-%dx%d.txt", state, w, h)) + if err := os.WriteFile(name, []byte(plain+"\n"), 0o644); err != nil { + t.Fatal(err) + } + } + } + } +} diff --git a/internal/ui/views/keys.go b/internal/ui/views/keys.go index 200c7ce..3ac556c 100644 --- a/internal/ui/views/keys.go +++ b/internal/ui/views/keys.go @@ -31,8 +31,9 @@ func keyGroups() []keyGroup { {"Projects", []Hotkey{{"n", "new project"}, {"e", "edit"}, {"d", "delete"}}}, {"Clients", []Hotkey{{"n", "new client"}, {"e", "edit"}, {"d", "delete"}}}, {"Reports", []Hotkey{ - {"enter", "show entries"}, {"e", "edit entry"}, {"f", "custom range"}, - {"t w m", "day, week, month"}, {"y a", "year, all time"}, + {"t w m y a", "today … all time"}, {"f", "custom range"}, + {"e", "export CSV"}, + {"enter", "show entries"}, {"e", "edit, in entries"}, }}, {"Forms", []Hotkey{ {"tab", "next field"}, {"shift+tab", "previous field"}, {"↑ ↓", "suggestions"}, diff --git a/internal/ui/views/reports.go b/internal/ui/views/reports.go index b892698..8cf0418 100644 --- a/internal/ui/views/reports.go +++ b/internal/ui/views/reports.go @@ -1,48 +1,91 @@ package views +// The Reports tab (ALI-2618), drawn from the design canvas's "Redesign · +// TUI · Reports" board (140×40) and the 90-column board's rules: range +// chips and the date range, four stat cards, hours by day as block bars, +// and a table of clients with their projects nested under them. Every +// number comes from internal/report, the same code behind "notch report", +// so the tab and the CLI agree for the same range. e exports the range's +// entries as CSV through report.WriteCSV; enter opens the entries behind +// the selected row, where e edits one. +// +// The drawing lives in reports_view.go and the export in +// reports_export.go. + import ( - "fmt" "strings" "time" "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/report" "github.com/aliasproject/notch/internal/theme" "github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/textinput" tea "github.com/charmbracelet/bubbletea" - "github.com/charmbracelet/lipgloss" -) - -// ── Column widths ───────────────────────────────────────────────────────────── - -const ( - rColGutter = theme.Gutter - rColHours = 12 - rColEntries = 12 - rColInv = 12 - rColPaid = 12 - rColEarned = 14 ) type reportsMode int const ( reportsModeView reportsMode = iota - reportsModeFilter + reportsModeCustom reportsModeEntries reportsModeEditEntry ) +// reportsPreset is the range chip that's on: one of report.Presets, or a +// custom range. +type reportsPreset string + +const ( + reportsPresetToday reportsPreset = "today" + reportsPresetWeek reportsPreset = "week" + reportsPresetMonth reportsPreset = "month" + reportsPresetYear reportsPreset = "year" + reportsPresetAll reportsPreset = "all" + reportsPresetCustom reportsPreset = "custom" +) + +// The custom range modal's focus order: the two dates, then its buttons. +const ( + customFieldFrom = iota + customFieldTo + customFieldApply + customFieldCancel + customFocusCount + customFieldCount = customFieldApply +) + +// reportLine is one row of the table: a client, or one of its projects +// under it. +type reportLine struct { + client bool + clientID int64 + projectID int64 // 0 on a client's row + name string + clientName string + report.Counts +} + type ReportsModel struct { db *db.DB width int height int mode reportsMode - rows []*model.ReportRow - cursor int - offset int // index into rows; see clampOffset + preset reportsPreset + rng report.Range + + // all is every entry, the running one included, as last loaded; rep is + // report.Build's report of it for rng, and lines its table rows. + all []*model.Entry + rep report.Report + lines []reportLine + loaded bool + + cursor int // index into lines + offset int // first visible line; see clampOffset entriesCursor int // index into the selected row's entries, in reportsModeEntries; see clampEntriesOffset entriesOffset int // scroll offset within entries; see clampEntriesOffset @@ -53,68 +96,67 @@ type ReportsModel struct { // editForm.errs. editForm timerForm + // The custom range modal: its two date inputs, the focused field or + // button, and each field's error. fromInput textinput.Model toInput textinput.Model - filterIdx int + focusIdx int + errs fieldErrors - dateFrom string - dateTo string - err string + // now is the clock the presets and the today bar read; nil means + // time.Now. Tests set it. + now func() time.Time + + err string } func NewReports(database *db.DB) ReportsModel { - // makeTextInput (not a bare textinput.New()) so these pick up the same - // background/prompt/cursor styling and width-safety margin as Timers' - // identical filter — see its doc comment and dateFilterInputWidth in - // common.go. - from := makeTextInput("YYYY-MM-DD", 10, dateFilterInputWidth) - to := makeTextInput("YYYY-MM-DD", 10, dateFilterInputWidth) - - // Default: current month - now := time.Now() - defaultFrom := fmt.Sprintf("%d-%02d-01", now.Year(), now.Month()) - defaultTo := now.Format("2006-01-02") - from.SetValue(defaultFrom) - to.SetValue(defaultTo) - - return ReportsModel{ + m := ReportsModel{ db: database, - fromInput: from, - toInput: to, - dateFrom: defaultFrom, - dateTo: defaultTo, + fromInput: makeTextInput("YYYY-MM-DD", 10, theme.FieldWidth), + toInput: makeTextInput("YYYY-MM-DD", 10, theme.FieldWidth), } + // The tab opens on this month, like "notch report" with no range. + m.setPreset(reportsPresetMonth) + return m +} + +func (m ReportsModel) clock() time.Time { + if m.now != nil { + return m.now() + } + return time.Now() } func (m ReportsModel) Init() tea.Cmd { return m.loadCmd() } -// IsBusy returns true when the view is in a mode that should capture all keystrokes. +// IsBusy reports whether the view captures every key: in the custom range +// modal (so q and the tab numbers type), the entries list and the edit +// form. func (m ReportsModel) IsBusy() bool { - return m.mode == reportsModeFilter || m.mode == reportsModeEntries || m.mode == reportsModeEditEntry + return m.mode != reportsModeView } -// Help returns the contextual hotkey string for the view's current mode, for -// display in the app-level hotkey bar (see app.go renderBottomBar). +// Help returns the contextual hotkeys for the view's current mode, for the +// app's hotkey line (see app.go renderBottomBar). func (m ReportsModel) Help() []Hotkey { switch m.mode { - case reportsModeFilter: - return []Hotkey{{"tab", "switch"}, {"enter", "apply"}, {"esc", "cancel"}} + case reportsModeCustom: + return []Hotkey{{"tab", "next"}, {"enter", "apply"}, {"esc", "cancel"}} case reportsModeEntries: return []Hotkey{{"↑ / ↓", "navigate"}, {"e", "edit"}, {"esc", "back"}} case reportsModeEditEntry: return m.editForm.help("Save") default: return []Hotkey{ - {"↑ / ↓", "navigate"}, - {"enter", "view entries"}, - {"f", "filter"}, {"t", "today"}, {"w", "week"}, {"m", "month"}, - {"y", "year"}, - {"a", "all"}, + {"f", "custom"}, + {"e", "export CSV"}, + {"↵", "entries"}, } } } @@ -122,85 +164,184 @@ func (m ReportsModel) Help() []Hotkey { func (m *ReportsModel) SetSize(w, h int) { m.width = w m.height = h + m.clampOffset() } -// -- messages ----------------------------------------------------------------- +// FieldErrors is how many fields of the open form need fixing, for the +// app's status line. +func (m ReportsModel) FieldErrors() int { + switch m.mode { + case reportsModeEditEntry: + return len(m.editForm.errs) + case reportsModeCustom: + return len(m.errs) + } + return 0 +} -type reportRowsMsg []*model.ReportRow +// ── Data ────────────────────────────────────────────────────────────────────── +// reportEntriesMsg carries every entry, the running one included, for the +// report to build from. +type reportEntriesMsg []*model.Entry + +// loadCmd loads every entry. report.Build keeps only the finished ones in +// the range, as "notch report" does with the same list. func (m ReportsModel) loadCmd() tea.Cmd { - from := m.dateFrom - to := m.dateTo + database := m.db return func() tea.Msg { - rows, err := m.db.ReportByProject(from, to) + all, err := database.ListEntries(0, "", "", true) if err != nil { return ErrMsg(err.Error()) } - // ReportByProject only aggregates (SUM/COUNT via GROUP BY) — it - // never attaches the underlying entries, so renderEntries' drill- - // down had nothing to show no matter which row was selected. - // Fetching them eagerly here (rather than lazily per selection) - // keeps the report's loading model simple: one command, one - // message, and report row counts are small enough (a handful of - // client/project combos, typically) that this isn't costly. - // includeRunning=false matches ReportByProject's own "e.end_time IS - // NOT NULL" filter, so a row's EntryCount/TotalHours always agree - // with how many entries actually show here. - for _, r := range rows { - entries, err := m.db.ListEntries(r.ProjectID, from, to, false) - if err != nil { - return ErrMsg(err.Error()) + return reportEntriesMsg(all) + } +} + +// rebuild makes the report for the range from the loaded entries, and its +// table rows: each client, then its projects. +func (m *ReportsModel) rebuild() { + m.rep = report.Build(m.all, m.rng) + m.lines = m.lines[:0] + for _, c := range m.rep.Clients { + m.lines = append(m.lines, reportLine{client: true, clientID: c.ID, name: c.Name, clientName: c.Name, Counts: c.Counts}) + for _, p := range c.Projects { + m.lines = append(m.lines, reportLine{clientID: c.ID, projectID: p.ID, name: p.Name, clientName: c.Name, Counts: p.Counts}) + } + } + if m.cursor >= len(m.lines) { + m.cursor = max(0, len(m.lines)-1) + } + m.clampOffset() +} + +// setPreset switches to a preset range as of now. +func (m *ReportsModel) setPreset(p reportsPreset) { + r, err := report.Preset(string(p), m.clock()) + if err != nil { + return + } + m.setRange(p, r) +} + +func (m *ReportsModel) setRange(p reportsPreset, r report.Range) { + m.preset, m.rng = p, r + m.cursor, m.offset = 0, 0 + m.rebuild() +} + +// running is the running entry, if it started in the range: the report +// leaves it out until it stops, and the view says so. +func (m ReportsModel) running() *model.Entry { + for _, e := range m.all { + if e.EndTime == nil && m.rng.Contains(e.StartTime.Local().Format("2006-01-02")) { + return e + } + } + return nil +} + +// selectedLine is the table row under the cursor, or nil. +func (m ReportsModel) selectedLine() *reportLine { + if m.cursor < 0 || m.cursor >= len(m.lines) { + return nil + } + return &m.lines[m.cursor] +} + +// lineEntries is the entries behind a row, newest first: the client's or +// the project's finished entries in the range, the same ones the row +// counts. +func (m ReportsModel) lineEntries(l *reportLine) []*model.Entry { + if l == nil { + return nil + } + in := report.Entries(m.all, m.rng) + var out []*model.Entry + for i := len(in) - 1; i >= 0; i-- { + e := in[i] + if l.client { + var cid int64 + if e.Project != nil { + cid = e.Project.ClientID + } + if cid == l.clientID { + out = append(out, e) } - r.Entries = entries + } else if e.ProjectID == l.projectID { + out = append(out, e) + } + } + return out +} + +// selectedEntries is the entries behind the selected row. +func (m ReportsModel) selectedEntries() []*model.Entry { + return m.lineEntries(m.selectedLine()) +} + +// selectedEntry is the entry under entriesCursor in the entries list, or +// nil. +func (m ReportsModel) selectedEntry() *model.Entry { + es := m.selectedEntries() + if m.entriesCursor < 0 || m.entriesCursor >= len(es) { + return nil + } + return es[m.entriesCursor] +} + +// entryByID finds a loaded entry. Handling reportsOpenEditMsg uses it: the +// cursor may have moved during the load, so the form opens on the entry +// asked for, not on whatever is selected now. +func (m ReportsModel) entryByID(id int64) *model.Entry { + for _, e := range m.all { + if e.ID == id { + return e } - return reportRowsMsg(rows) } + return nil } -// -- Update ------------------------------------------------------------------- +// ── Update ──────────────────────────────────────────────────────────────────── type reportsKeyMap struct { Up key.Binding Down key.Binding - Filter key.Binding - Apply key.Binding + Custom key.Binding + Enter key.Binding Edit key.Binding + Export key.Binding Cancel key.Binding Today key.Binding Week key.Binding Month key.Binding Year key.Binding All key.Binding - Next key.Binding - Prev key.Binding } var reportsKeys = reportsKeyMap{ Up: key.NewBinding(key.WithKeys("up", "k")), Down: key.NewBinding(key.WithKeys("down", "j")), - Filter: key.NewBinding(key.WithKeys("f")), - Apply: key.NewBinding(key.WithKeys("enter")), + Custom: key.NewBinding(key.WithKeys("f")), + Enter: key.NewBinding(key.WithKeys("enter")), Edit: key.NewBinding(key.WithKeys("e")), + Export: key.NewBinding(key.WithKeys("e")), Cancel: key.NewBinding(key.WithKeys("esc")), Today: key.NewBinding(key.WithKeys("t")), Week: key.NewBinding(key.WithKeys("w")), Month: key.NewBinding(key.WithKeys("m")), Year: key.NewBinding(key.WithKeys("y")), All: key.NewBinding(key.WithKeys("a")), - Next: key.NewBinding(key.WithKeys("tab")), - Prev: key.NewBinding(key.WithKeys("shift+tab")), } func (m ReportsModel) Update(msg tea.Msg) (ReportsModel, tea.Cmd) { switch msg := msg.(type) { - - case reportRowsMsg: - m.rows = []*model.ReportRow(msg) - if m.cursor >= len(m.rows) && m.cursor > 0 { - m.cursor = len(m.rows) - 1 + case reportEntriesMsg: + m.all, m.loaded, m.err = []*model.Entry(msg), true, "" + m.rebuild() + if m.mode == reportsModeEntries || m.mode == reportsModeEditEntry { + m.clampEntriesCursor() } - m.clampOffset() - m.err = "" return m, nil case reportsOpenEditMsg: @@ -208,8 +349,8 @@ func (m ReportsModel) Update(msg tea.Msg) (ReportsModel, tea.Cmd) { case tea.KeyMsg: switch m.mode { - case reportsModeFilter: - return m.updateFilter(msg) + case reportsModeCustom: + return m.updateCustom(msg) case reportsModeEntries: return m.updateEntries(msg) case reportsModeEditEntry: @@ -222,6 +363,24 @@ func (m ReportsModel) Update(msg tea.Msg) (ReportsModel, tea.Cmd) { } func (m ReportsModel) updateView(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { + presets := []struct { + k key.Binding + p reportsPreset + }{ + {reportsKeys.Today, reportsPresetToday}, + {reportsKeys.Week, reportsPresetWeek}, + {reportsKeys.Month, reportsPresetMonth}, + {reportsKeys.Year, reportsPresetYear}, + {reportsKeys.All, reportsPresetAll}, + } + for _, p := range presets { + if key.Matches(msg, p.k) { + m.setPreset(p.p) + // Draw from what's loaded now, and reload in case another + // process has logged time since. + return m, m.loadCmd() + } + } switch { case key.Matches(msg, reportsKeys.Up): if m.cursor > 0 { @@ -229,76 +388,132 @@ func (m ReportsModel) updateView(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { m.clampOffset() } case key.Matches(msg, reportsKeys.Down): - if m.cursor < len(m.rows)-1 { + if m.cursor < len(m.lines)-1 { m.cursor++ m.clampOffset() } - case key.Matches(msg, reportsKeys.Apply): - // Opens the selected row's full entries view — its own dedicated - // screen (matching how editing a timer or filtering by date fully - // replaces the view), rather than a capped inline preview - // competing with this table for space. See renderEntriesView. - if m.cursor >= 0 && m.cursor < len(m.rows) { + case key.Matches(msg, reportsKeys.Enter): + // The entries behind the row get their own screen, with the + // selected entry's details under them; e edits one from there. + if m.selectedLine() != nil { m.mode = reportsModeEntries - m.entriesCursor = 0 - m.entriesOffset = 0 + m.entriesCursor, m.entriesOffset = 0, 0 } - case key.Matches(msg, reportsKeys.Filter): - m.mode = reportsModeFilter - m.filterIdx = 0 + case key.Matches(msg, reportsKeys.Custom): + return m.openCustom(), textinput.Blink + case key.Matches(msg, reportsKeys.Export): + return m, m.exportCmd() + } + return m, nil +} + +// ── Custom range modal ──────────────────────────────────────────────────────── + +// openCustom opens the custom range modal on the current range's dates. +func (m ReportsModel) openCustom() ReportsModel { + m.mode = reportsModeCustom + m.errs = nil + m.fromInput.SetValue(m.rng.From) + m.toInput.SetValue(m.rng.To) + m.fromInput.CursorEnd() + m.toInput.CursorEnd() + return m.focusCustom(customFieldFrom) +} + +func (m ReportsModel) focusCustom(idx int) ReportsModel { + m.fromInput.Blur() + m.toInput.Blur() + m.focusIdx = idx + switch idx { + case customFieldFrom: m.fromInput.Focus() - m.toInput.Blur() - return m, textinput.Blink - case key.Matches(msg, reportsKeys.Today): - today := time.Now().Format("2006-01-02") - m.dateFrom = today - m.dateTo = today - m.fromInput.SetValue(today) - m.toInput.SetValue(today) - return m, m.loadCmd() - case key.Matches(msg, reportsKeys.Week): - now := time.Now() - weekday := int(now.Weekday()) - if weekday == 0 { - weekday = 7 + case customFieldTo: + m.toInput.Focus() + } + return m +} + +func (m ReportsModel) updateCustom(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { + switch { + case key.Matches(msg, formKeys.Cancel): + m.mode, m.errs = reportsModeView, nil + m = m.focusCustom(customFieldFrom) + m.fromInput.Blur() + return m, nil + case key.Matches(msg, formKeys.NextField): + return m.focusCustom((m.focusIdx + 1) % customFocusCount), textinput.Blink + case key.Matches(msg, formKeys.PrevField): + return m.focusCustom((m.focusIdx - 1 + customFocusCount) % customFocusCount), textinput.Blink + case key.Matches(msg, formKeys.Submit), msg.String() == " " && m.focusIdx >= customFieldCount: + if m.focusIdx == customFieldCancel { + m.mode, m.errs = reportsModeView, nil + m.fromInput.Blur() + m.toInput.Blur() + return m, nil + } + return m.applyCustom() + } + if m.focusIdx >= customFieldCount { + return m, nil + } + // Typing goes to the focused date, and changing it clears its error. + in := &m.fromInput + if m.focusIdx == customFieldTo { + in = &m.toInput + } + before := in.Value() + var cmd tea.Cmd + *in, cmd = in.Update(msg) + if in.Value() != before { + delete(m.errs, m.focusIdx) + } + return m, cmd +} + +// Custom range errors, under their fields. +const ( + errCustomDate = "Use a date like 2026-12-03, or leave it blank" + errCustomOrder = "The last day can’t be before the first" +) + +// applyCustom checks the two dates and, if they're good, switches to +// their range. Either can be blank, which leaves that side open. +func (m ReportsModel) applyCustom() (ReportsModel, tea.Cmd) { + from := strings.TrimSpace(m.fromInput.Value()) + to := strings.TrimSpace(m.toInput.Value()) + m.errs = fieldErrors{} + for idx, v := range map[int]string{customFieldFrom: from, customFieldTo: to} { + if _, err := report.ParseRange(v, ""); v != "" && err != nil { + m.errs[idx] = errCustomDate + } + } + if len(m.errs) == 0 { + r, err := report.ParseRange(from, to) + if err != nil { + m.errs[customFieldTo] = errCustomOrder + } else { + m.errs = nil + m.mode = reportsModeView + m.fromInput.Blur() + m.toInput.Blur() + m.setRange(reportsPresetCustom, r) + return m, m.loadCmd() + } + } + // Focus the first field that needs fixing. + for _, idx := range []int{customFieldFrom, customFieldTo} { + if _, bad := m.errs[idx]; bad { + return m.focusCustom(idx), textinput.Blink } - monday := now.AddDate(0, 0, -(weekday - 1)) - m.dateFrom = monday.Format("2006-01-02") - m.dateTo = now.Format("2006-01-02") - m.fromInput.SetValue(m.dateFrom) - m.toInput.SetValue(m.dateTo) - return m, m.loadCmd() - case key.Matches(msg, reportsKeys.Month): - now := time.Now() - m.dateFrom = fmt.Sprintf("%d-%02d-01", now.Year(), now.Month()) - m.dateTo = now.Format("2006-01-02") - m.fromInput.SetValue(m.dateFrom) - m.toInput.SetValue(m.dateTo) - return m, m.loadCmd() - case key.Matches(msg, reportsKeys.Year): - now := time.Now() - m.dateFrom = fmt.Sprintf("%d-01-01", now.Year()) - m.dateTo = now.Format("2006-01-02") - m.fromInput.SetValue(m.dateFrom) - m.toInput.SetValue(m.dateTo) - return m, m.loadCmd() - case key.Matches(msg, reportsKeys.All): - m.dateFrom = "" - m.dateTo = "" - m.fromInput.SetValue("") - m.toInput.SetValue("") - return m, m.loadCmd() } return m, nil } -// updateEntries handles input while viewing a single row's full entries -// list (reportsModeEntries): ↑/↓ moves the selection (auto-scrolling to -// keep it visible, same shape as TimersModel's own list — see -// clampEntriesOffset), 'e' opens the selected entry for editing, esc goes -// back to the report table. +// ── Entries list ────────────────────────────────────────────────────────────── + +// updateEntries handles keys in the entries behind a row: ↑/↓ moves the +// selection, e edits the selected entry, esc goes back to the report. func (m ReportsModel) updateEntries(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { - r := m.selectedRow() switch { case key.Matches(msg, reportsKeys.Cancel): m.mode = reportsModeView @@ -308,7 +523,7 @@ func (m ReportsModel) updateEntries(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { m.clampEntriesOffset() } case key.Matches(msg, reportsKeys.Down): - if r != nil && m.entriesCursor < len(r.Entries)-1 { + if m.entriesCursor < len(m.selectedEntries())-1 { m.entriesCursor++ m.clampEntriesOffset() } @@ -320,10 +535,24 @@ func (m ReportsModel) updateEntries(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { return m, nil } -// updateEditEntry handles input while editing a single entry -// (reportsModeEditEntry). Field navigation, dropdowns, and typing all -// delegate to updateTimerFormFields — the same logic TimersModel's own -// New/Edit Timer form uses — so only Cancel/Save need handling here. +// clampEntriesCursor keeps the entries cursor on an entry after a reload. +// When the row itself has gone (its last entry was moved out of it, say), +// it goes back to the report. +func (m *ReportsModel) clampEntriesCursor() { + n := len(m.selectedEntries()) + if n == 0 && m.mode == reportsModeEntries { + m.mode = reportsModeView + return + } + if m.entriesCursor >= n { + m.entriesCursor = max(0, n-1) + } + m.clampEntriesOffset() +} + +// updateEditEntry handles keys in the Edit entry form. Field navigation, +// dropdowns and typing go to updateTimerFormFields, the same logic as the +// Timers tab's form, so only cancel and save are handled here. func (m ReportsModel) updateEditEntry(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { action, cmd := updateTimerFormFields(&m.editForm, msg) switch action { @@ -336,10 +565,8 @@ func (m ReportsModel) updateEditEntry(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { return m, cmd } -// submitEditEntry validates the edit form and, if valid, writes the change -// and reloads this report's rows so the table/entries list reflects it — -// the Reports-side counterpart to TimersModel.submitForm's edit branch, -// sharing the same validateTimerForm and submitEdit. +// submitEditEntry validates the edit form and, if it's good, saves the +// change and reloads the report, so the table and the entries list show it. func (m ReportsModel) submitEditEntry(now time.Time) (ReportsModel, tea.Cmd) { v, errs := validateTimerForm(m.editForm, now) if len(errs) > 0 { @@ -354,22 +581,17 @@ func (m ReportsModel) submitEditEntry(now time.Time) (ReportsModel, tea.Cmd) { return m, cmd } -// reportsOpenEditMsg carries the data needed to populate the edit-entry -// form for a specific entry. It's a distinct type from Timers' -// openFormMsg deliberately: app.go broadcasts every non-key tea.Msg to -// *all* tabs (not just the active one — see its Update comment "Everything -// else → all tabs"), so reusing openFormMsg here would also pop open the -// real, currently-inactive Timers tab's own edit form for the same entry. +// reportsOpenEditMsg carries what the Edit entry form needs for one entry. +// It's its own type, not Timers' openFormMsg: app.go sends every message +// that isn't a key to every tab, so an openFormMsg would also open the +// Timers tab's form behind this one. type reportsOpenEditMsg struct { entryID int64 clients []*model.Client projects []*model.Project } -// openEditEntryCmd fetches the clients/projects needed to populate the -// edit form for entryID — mirrors TimersModel.openFormCmd, but returns -// reportsOpenEditMsg instead of the shared openFormMsg (see its doc -// comment for why). +// openEditEntryCmd loads the clients and projects the edit form offers. func (m ReportsModel) openEditEntryCmd(entryID int64) tea.Cmd { return func() tea.Msg { clients, err := m.db.ListClients() @@ -384,633 +606,17 @@ func (m ReportsModel) openEditEntryCmd(entryID int64) tea.Cmd { } } -// handleOpenEditEntry populates m.editForm from the entry named in msg and -// switches to reportsModeEditEntry — mirrors -// TimersModel.handleOpenForm's population logic exactly (same field -// mapping), since it's populating the same kind of form. +// handleOpenEditEntry fills the edit form from the entry msg names and +// opens it. func (m ReportsModel) handleOpenEditEntry(msg reportsOpenEditMsg) ReportsModel { e := m.entryByID(msg.entryID) if e == nil { m.err = "Entry not found" return m } - f := newTimerForm(msg.clients, msg.projects) f.fill(e) - m.editForm = f m.mode = reportsModeEditEntry return m } - -func (m ReportsModel) updateFilter(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { - switch { - case key.Matches(msg, reportsKeys.Cancel): - m.mode = reportsModeView - m.fromInput.Blur() - m.toInput.Blur() - return m, nil - - case key.Matches(msg, reportsKeys.Apply): - m.dateFrom = strings.TrimSpace(m.fromInput.Value()) - m.dateTo = strings.TrimSpace(m.toInput.Value()) - m.mode = reportsModeView - m.fromInput.Blur() - m.toInput.Blur() - return m, m.loadCmd() - - case key.Matches(msg, reportsKeys.Next): - m.fromInput.Blur() - m.toInput.Blur() - m.filterIdx = (m.filterIdx + 1) % 2 - if m.filterIdx == 0 { - m.fromInput.Focus() - } else { - m.toInput.Focus() - } - return m, textinput.Blink - - case key.Matches(msg, reportsKeys.Prev): - m.fromInput.Blur() - m.toInput.Blur() - m.filterIdx = (m.filterIdx - 1 + 2) % 2 - if m.filterIdx == 0 { - m.fromInput.Focus() - } else { - m.toInput.Focus() - } - return m, textinput.Blink - } - - // Forward to focused input - var cmd tea.Cmd - if m.filterIdx == 0 { - m.fromInput, cmd = m.fromInput.Update(msg) - } else { - m.toInput, cmd = m.toInput.Update(msg) - } - return m, cmd -} - -// -- View --------------------------------------------------------------------- - -func (m ReportsModel) View() string { - header := m.renderHeader() - - // Filter mode fully replaces the body (matches TimersModel.viewList's - // identical branch) rather than showing the filter form above the - // table: the table is about to change anyway, so leaving the old rows - // visible underneath the form while editing the range just reads as - // stale clutter. Consistent with Timers keeps the two date-range - // filters — which already share renderDateFilterBar — behaving - // identically everywhere they appear. - if m.mode == reportsModeFilter { - return header + "\n\n" + m.renderFilterBar() - } - - // Entries mode also fully replaces the body — see renderEntriesView. - if m.mode == reportsModeEntries { - return m.renderEntriesView() - } - - // Editing an entry does too, sharing TimersModel's own form renderer — - // see updateTimerFormFields' doc comment for why the form logic lives - // as free functions rather than TimersModel methods. - if m.mode == reportsModeEditEntry { - w, h := usableWidth(m.width), max(1, m.height-2) - return modalOver(m.renderEntriesView(), w, h, m.editForm.view(w, h, "Save")) - } - - var sb strings.Builder - sb.WriteString(header) - sb.WriteString("\n\n") - - if len(m.rows) == 0 { - sb.WriteString(StyleMuted.Render("No data for the selected period.")) - return sb.String() - } - - sb.WriteString(m.renderTable()) - sb.WriteString("\n") - sb.WriteString(m.renderTotals()) - - return sb.String() -} - -func (m ReportsModel) renderHeader() string { - var rangeStr string - switch { - case m.dateFrom == "" && m.dateTo == "": - rangeStr = "All time" - case m.dateFrom == m.dateTo && m.dateFrom != "": - rangeStr = m.dateFrom - default: - from := m.dateFrom - if from == "" { - from = "—" - } - to := m.dateTo - if to == "" { - to = "—" - } - rangeStr = from + " → " + to - } - - return StyleTitle.Render("Reports") + - StyleMuted.Render(" · ") + - StyleMuted.Render(rangeStr) -} - -func (m ReportsModel) renderFilterBar() string { - return renderDateFilterBar(m.fromInput, m.toInput, m.filterIdx) -} - -// selectedRow returns the report row under the table cursor, or nil if -// rows is empty or the cursor is (transiently) out of bounds. -func (m ReportsModel) selectedRow() *model.ReportRow { - if m.cursor < 0 || m.cursor >= len(m.rows) { - return nil - } - return m.rows[m.cursor] -} - -// selectedEntry returns the entry under entriesCursor within the currently -// selected report row, or nil if there's no selection or the cursor is -// (transiently) out of bounds. -func (m ReportsModel) selectedEntry() *model.Entry { - r := m.selectedRow() - if r == nil || m.entriesCursor < 0 || m.entriesCursor >= len(r.Entries) { - return nil - } - return r.Entries[m.entriesCursor] -} - -// entryByID searches every loaded row's entries for the one matching id. -// Used when handling reportsOpenEditMsg: the async DB round-trip to fetch -// clients/projects for the edit form leaves a gap where the user could in -// principle have moved the cursor, so this re-finds the entry by ID rather -// than trusting selectedEntry() still points at the same one. -func (m ReportsModel) entryByID(id int64) *model.Entry { - for _, r := range m.rows { - for _, e := range r.Entries { - if e.ID == id { - return e - } - } - } - return nil -} - -// mainColWidths returns the CLIENT and PROJECT column widths so the report -// table spans the full available content width. The numeric columns stay fixed -// (each includes its cell padding). -func (m ReportsModel) mainColWidths() (clientW, projectW int) { - avail := usableWidth(m.width) - rest := avail - rColGutter - rColHours - rColEntries - rColInv - rColPaid - rColEarned - if rest < 0 { - rest = 0 - } - clientW = rest / 2 - projectW = rest - clientW - return clientW, projectW -} - -// rowsBudget returns how many report-table rows fit given the current view -// height, after reserving room for the fixed chrome (header + blank + table -// header + divider) and the fixed 5-line totals section (divider + totals -// row + blank + 2-line summary cards — see renderTotals). Doesn't need to -// reserve room for a row's entries any more — those show in their own full -// screen now (reportsModeEntries / renderEntriesView), not inline here. -func (m ReportsModel) rowsBudget() int { - // m.height is the column height including its Padding(1, 3), so the - // usable content area is m.height - 2. Fixed chrome: header + blank + - // table header + divider = 4. - budget := m.height - 2 - 4 - 5 - if budget < 1 { - budget = 1 - } - return budget -} - -// clampOffset keeps the cursor's row inside the visible [offset, -// offset+budget) window, scrolling only when it reaches the edge — mirrors -// TimersModel.clampOffset (this table has no day-grouping, so it's the -// simpler flat-list version). -func (m *ReportsModel) clampOffset() { - budget := m.rowsBudget() - n := len(m.rows) - if n <= budget { - m.offset = 0 - return - } - if m.cursor < m.offset { - m.offset = m.cursor - } - if m.offset > n-budget { - m.offset = n - budget - } - if m.cursor >= m.offset+budget { - m.offset = m.cursor - budget + 1 - } - if m.offset < 0 { - m.offset = 0 - } -} - -func (m ReportsModel) renderTable() string { - clientW, projectW := m.mainColWidths() - totalW := usableWidth(m.width) - - hdr := RowPrefix(false) + - StyleTableHeader.Width(clientW).Render(truncate("Client", clientW-2)) + - StyleTableHeader.Width(projectW).Render(truncate("Project", projectW-2)) + - StyleTableHeader.Width(rColHours).Align(lipgloss.Right).Render("Hours") + - StyleTableHeader.Width(rColEntries).Align(lipgloss.Right).Render("Entries") + - StyleTableHeader.Width(rColInv).Align(lipgloss.Right).Render("Invoiced") + - StyleTableHeader.Width(rColPaid).Align(lipgloss.Right).Render("Paid") + - StyleTableHeader.Width(rColEarned).Align(lipgloss.Right).Render("Earned") - - m.clampOffset() - budget := m.rowsBudget() - start := m.offset - if start < 0 { - start = 0 - } - end := start + budget - if end > len(m.rows) { - end = len(m.rows) - } - visible := m.rows[start:end] - - // divider doubles as a scroll indicator (▲ = more above, ▼ = more - // below), matching TimersModel.viewList's identical convention. - runes := []rune(strings.Repeat("─", totalW)) - if start > 0 { - runes[0] = '▲' - } - if end < len(m.rows) { - runes[len(runes)-1] = '▼' - } - divider := StyleTableDiv.Render(string(runes)) - - var rows []string - rows = append(rows, hdr, divider) - for i, r := range visible { - idx := start + i - rows = append(rows, m.renderRow(r, idx == m.cursor)) - } - - return strings.Join(rows, "\n") -} - -func (m ReportsModel) renderRow(r *model.ReportRow, selected bool) string { - prefix := RowPrefix(selected) - clientW, projectW := m.mainColWidths() - - hoursStr := fmt.Sprintf("%.2fh", r.TotalHours) - entriesStr := fmt.Sprintf("%d", r.EntryCount) - invStr := fmt.Sprintf("%d/%d", r.Invoiced, r.EntryCount) - paidStr := fmt.Sprintf("%d/%d", r.Paid, r.EntryCount) - earnedStr := fmt.Sprintf("$%.2f", r.Earnings) - - var base lipgloss.Style - if selected { - base = StyleTableRowSel - } else { - base = StyleTableRow - } - - // colour-coded sub-columns only when not selected - earnedStyle := base - invStyle := base - paidStyle := base - hoursStyle := base - - if !selected { - // Based on StyleTableRow (not a bare lipgloss.NewStyle()) so these - // color-coded cells keep the same Padding(0, 1) as the header and the - // selected-row style — otherwise their text starts one column left of - // where the column header sits. - hoursStyle = StyleTableRow.Foreground(cHighlight) - if r.Earnings > 0 { - earnedStyle = StyleTableRow.Foreground(cGreen) - } else { - earnedStyle = StyleTableRow.Foreground(cDim) - } - switch { - case r.Invoiced == r.EntryCount && r.EntryCount > 0: - invStyle = StyleTableRow.Foreground(cAccent) - case r.Invoiced > 0: - invStyle = StyleTableRow.Foreground(cAmber) - default: - invStyle = StyleTableRow.Foreground(cDim) - } - switch { - case r.Paid == r.EntryCount && r.EntryCount > 0: - paidStyle = StyleTableRow.Foreground(cGreen) - case r.Paid > 0: - paidStyle = StyleTableRow.Foreground(cAmber) - default: - paidStyle = StyleTableRow.Foreground(cDim) - } - } - - return prefix + - base.Width(clientW).Render(truncate(r.ClientName, clientW-3)) + - base.Width(projectW).Render(truncate(r.ProjectName, projectW-3)) + - hoursStyle.Width(rColHours).Align(lipgloss.Right).Render(hoursStr) + - base.Width(rColEntries).Align(lipgloss.Right).Render(entriesStr) + - invStyle.Width(rColInv).Align(lipgloss.Right).Render(invStr) + - paidStyle.Width(rColPaid).Align(lipgloss.Right).Render(paidStr) + - earnedStyle.Width(rColEarned).Align(lipgloss.Right).Render(earnedStr) -} - -func (m ReportsModel) renderTotals() string { - var totalHours, totalEarnings float64 - var totalEntries, totalInvoiced, totalPaid int - for _, r := range m.rows { - totalHours += r.TotalHours - totalEarnings += r.Earnings - totalEntries += r.EntryCount - totalInvoiced += r.Invoiced - totalPaid += r.Paid - } - - clientW, projectW := m.mainColWidths() - totalW := usableWidth(m.width) - divider := StyleTableDiv.Render(strings.Repeat("─", totalW)) - - totals := RowPrefix(false) + - StyleTableHeader.Width(clientW+projectW).Render(truncate("TOTALS", clientW+projectW-2)) + - StyleTableHeader.Copy().Foreground(cHighlight).Width(rColHours).Align(lipgloss.Right).Render(fmt.Sprintf("%.2fh", totalHours)) + - StyleTableHeader.Width(rColEntries).Align(lipgloss.Right).Render(fmt.Sprintf("%d", totalEntries)) + - StyleTableHeader.Width(rColInv).Align(lipgloss.Right).Render(fmt.Sprintf("%d/%d", totalInvoiced, totalEntries)) + - StyleTableHeader.Width(rColPaid).Align(lipgloss.Right).Render(fmt.Sprintf("%d/%d", totalPaid, totalEntries)) + - StyleTableHeader.Copy().Foreground(cGreen).Width(rColEarned).Align(lipgloss.Right).Render(fmt.Sprintf("$%.2f", totalEarnings)) - - cards := m.renderSummaryCards(totalHours, totalEarnings, totalEntries, totalInvoiced, totalPaid) - - // Plain "\n" join, not lipgloss.JoinVertical — see padCellToTwoLines in - // common.go for why: JoinVertical would pad the narrower `cards` line(s) to - // the divider's width using unstyled spaces, punching a hole to their right. - return divider + "\n" + totals + "\n\n" + cards -} - -func (m ReportsModel) renderSummaryCards(hours, earned float64, entries, invoiced, paid int) string { - outstanding := earned - for _, r := range m.rows { - if r.Paid == r.EntryCount && r.EntryCount > 0 { - outstanding -= r.Earnings - } - } - unpaidEntries := entries - paid - - card := func(label, value string, vs lipgloss.Style, withBorder bool) string { - // The box style itself carries Background(cBg): lipgloss's own Padding - // fill (and the fill it adds to left-align the shorter of label/value) - // respects the style's background, unlike lipgloss.JoinVertical's raw - // unstyled padding — see padCellToTwoLines in common.go. Margin is a - // *separate* property in lipgloss (MarginBackground, distinct from - // Background) and defaults to no color at all, so MarginRight needs its - // own explicit background or the gap between cards shows the terminal's - // default background instead of cBg. - return lipgloss.NewStyle(). - Border(lipgloss.NormalBorder(), false, false, false, withBorder). - BorderForeground(cBorder). - BorderBackground(cBg). - Background(cBg). - PaddingLeft(2). - MarginRight(4). - MarginBackground(cBg). - Render(StyleMuted.Render(label) + "\n" + vs.Bold(true).Background(cBg).Render(value)) - } - - uninvStyle := StyleDanger - if unpaidEntries == 0 { - uninvStyle = StyleSuccess - } - - return lipgloss.JoinHorizontal(lipgloss.Top, - // No left border on the first card — there's nothing to its left to - // separate it from, so the bar just looked like a stray leading rule. - card("Total Hours", fmt.Sprintf("%.2f h", hours), lipgloss.NewStyle().Foreground(cHighlight), false), - card("Total Earned", fmt.Sprintf("$%.2f", earned), StyleSuccess, true), - card("Outstanding", fmt.Sprintf("$%.2f", outstanding), StyleWarning, true), - card("Uninvoiced", fmt.Sprintf("%d entries", unpaidEntries), uninvStyle, true), - ) -} - -// entryCols returns the column widths for both renderEntriesView's table and -// its scroll-budget math, so the two can't drift apart. TASK expands to fill -// whatever's left. -func (m ReportsModel) entryCols() (date, task, dur, earned, status int) { - date, dur, earned, status = 14, 12, 12, 12 - // theme.Gutter = RowPrefix's width. Regression note: this used to subtract - // a hardcoded 8 here (a stale guess at the status column's width, from - // before it was widened to 12 to match the other fixed columns) instead - // of the actual `status` value — every row rendered 4 columns wider - // than totalW as a result. Since app.go's outer column wraps the whole - // view in Width(cw), and lipgloss word-wraps (never truncates) content - // wider than that, every entry row silently wrapped onto an extra - // line — doubling the effective table height and overflowing well past - // entriesRowsBudget, which pushed the header (and everything above the - // overflow) off the top of the screen. - task = usableWidth(m.width) - (theme.Gutter + date + dur + earned + status) - if task < 20 { - // Narrow terminal: tighten the fixed columns to their widest - // content ("Sep 10, 2026", "12:34:56", "$1234.56", "invoiced") - // before squeezing TASK. Flooring TASK at 20 without doing this - // made the row wider than the outer column at widths under ~80, - // so every header and entry row wrapped onto a second line. - date, dur, earned, status = 13, 10, 10, 9 - task = usableWidth(m.width) - (theme.Gutter + date + dur + earned + status) - if task < 8 { - task = 8 - } - } - return date, task, dur, earned, status -} - -// renderEntryDetail shows the currently selected entry's Started/End time, -// Notes (if any), and billing status — mirrors TimersModel.renderDetail -// (including reusing invoiceLabel) so the two views' detail panes look and -// behave identically. -func (m ReportsModel) renderEntryDetail(e *model.Entry) string { - started := e.StartTime.Local().Format("Jan 2, 2006 3:04 PM") - dateLine := StyleMuted.Render("Started ") + StyleTableRow.Render(started) - if e.EndTime != nil { - dateLine += StyleMuted.Render(" – ") + StyleTableRow.Render(e.EndTime.Local().Format("3:04 PM")) - } - - notesLine := StyleMuted.Render(noteDetailLabel) + formatNoteDetail(e.Notes, usableWidth(m.width)) - statusLine := StyleMuted.Render("Status ") + invoiceLabel(e) - return strings.Join([]string{dateLine, notesLine, statusLine}, "\n") -} - -// entriesRowsBudget returns how many entry rows fit in the full entries -// view: header + blank + table header + divider + blank before the detail -// pane = 5 fixed lines, plus the detail pane's own fixed height (see -// entryDetailLines — mirrors TimersModel.rowsBudget's identical dependency -// on its own detail pane). -func (m ReportsModel) entriesRowsBudget() int { - detailLines := 1 - if m.selectedEntry() != nil { - detailLines = entryDetailLines - } - budget := m.height - 2 - 5 - detailLines - if budget < 1 { - budget = 1 - } - return budget -} - -// clampEntriesOffset keeps entriesCursor's row inside the visible [offset, -// offset+budget) window of the selected row's entries, scrolling only when -// it reaches the edge — mirrors TimersModel.clampOffset (this list has no -// day-grouping, so it's the simpler flat-list version). -func (m *ReportsModel) clampEntriesOffset() { - r := m.selectedRow() - if r == nil { - m.entriesOffset = 0 - return - } - n := len(r.Entries) - budget := m.entriesRowsBudget() - if n <= budget { - m.entriesOffset = 0 - return - } - if m.entriesCursor < m.entriesOffset { - m.entriesOffset = m.entriesCursor - } - if m.entriesOffset > n-budget { - m.entriesOffset = n - budget - } - if m.entriesCursor >= m.entriesOffset+budget { - m.entriesOffset = m.entriesCursor - budget + 1 - } - if m.entriesOffset < 0 { - m.entriesOffset = 0 - } -} - -// renderEntriesView shows the full, scrollable list of entries for the -// currently selected report row — its own dedicated screen (see -// reportsModeEntries) rather than a capped inline preview competing with -// the report table for space, so a client/project with many logged -// sessions is fully browsable, not truncated with a "… and N more" note. -// The selected entry's Started/End/Notes/Status show in a detail pane -// below the table, mirroring TimersModel.viewList's identical layout. -func (m ReportsModel) renderEntriesView() string { - r := m.selectedRow() - if r == nil { - return m.renderHeader() - } - - header := StyleTitle.Render(r.ClientName+" › "+r.ProjectName) + - StyleMuted.Render(" · ") + - StyleMuted.Render(fmt.Sprintf("%.2fh billed · $%.2f", r.TotalHours, r.Earnings)) - - if len(r.Entries) == 0 { - return header + "\n\n" + StyleMuted.Render("No entries for this period.") - } - - eColDate, eColTask, eColDur, eColEarned, eColStatus := m.entryCols() - totalW := usableWidth(m.width) - - hdr := RowPrefix(false) + - StyleTableHeader.Width(eColDate).Render("Date") + - StyleTableHeader.Width(eColTask).Render("Task") + - StyleTableHeader.Width(eColDur).Align(lipgloss.Right).Render("Duration") + - StyleTableHeader.Width(eColEarned).Align(lipgloss.Right).Render("Earned") + - StyleTableHeader.Width(eColStatus).Render("Status") - - m.clampEntriesOffset() - budget := m.entriesRowsBudget() - start := m.entriesOffset - if start < 0 { - start = 0 - } - end := start + budget - if end > len(r.Entries) { - end = len(r.Entries) - } - visible := r.Entries[start:end] - - // divider doubles as a scroll indicator (▲ = more above, ▼ = more - // below), matching renderTable's identical convention. - runes := []rune(strings.Repeat("─", totalW)) - if start > 0 { - runes[0] = '▲' - } - if end < len(r.Entries) { - runes[len(runes)-1] = '▼' - } - divider := StyleTableDiv.Render(string(runes)) - - rows := []string{hdr, divider} - for i, e := range visible { - idx := start + i - sel := idx == m.entriesCursor - - base := StyleTableRow - if sel { - base = StyleTableRowSel - } - - date := e.StartTime.Local().Format("Jan 2, 2006") - task := truncate(e.Task, eColTask-3) - dur := model.FormatDuration(e.Duration()) - - var earnedStr string - if r.HourlyRate > 0 { - earnedStr = fmt.Sprintf("$%.2f", e.Earnings(r.HourlyRate)) - } else { - earnedStr = "—" - } - - // rowBg mirrors `base`'s own background (cBgAlt when selected, cBg - // otherwise) so the status cell below — which needs its own fixed - // foreground independent of `base` — still completes the selected - // row's tint instead of leaving a plain-cBg gap in it. - rowBg := cBg - if sel { - rowBg = cBgAlt - } - var statusStr string - switch { - case e.Paid: - statusStr = StyleSuccess.Background(rowBg).Width(eColStatus).Render("paid") - case e.Invoiced: - statusStr = StyleAccent.Background(rowBg).Width(eColStatus).Render("invoiced") - default: - statusStr = StyleMuted.Background(rowBg).Width(eColStatus).Render("pending") - } - - row := RowPrefix(sel) + - base.Width(eColDate).Render(date) + - base.Width(eColTask).Render(task) + - base.Width(eColDur).Align(lipgloss.Right).Render(dur) + - base.Width(eColEarned).Align(lipgloss.Right).Render(earnedStr) + - statusStr - - rows = append(rows, row) - } - - tableStr := strings.Join(rows, "\n") - detail := "" - if e := m.selectedEntry(); e != nil { - detail = m.renderEntryDetail(e) - } - - return header + "\n\n" + tableStr + "\n\n" + detail -} - -// FieldErrors is how many fields of the Edit entry form need fixing, for -// the app's status line. -func (m ReportsModel) FieldErrors() int { - if m.mode == reportsModeEditEntry { - return len(m.editForm.errs) - } - return 0 -} diff --git a/internal/ui/views/reports_export.go b/internal/ui/views/reports_export.go new file mode 100644 index 0000000..6815657 --- /dev/null +++ b/internal/ui/views/reports_export.go @@ -0,0 +1,181 @@ +package views + +// CSV export from the Reports tab (ALI-2618): e writes the range's entries +// with report.WriteCSV, the same rows as "notch report --csv", to a new +// file in the downloads folder, and the status line says where. + +import ( + "bufio" + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "strconv" + "strings" + + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/report" + tea "github.com/charmbracelet/bubbletea" +) + +// exportCmd writes the range's finished entries to a new CSV file. +func (m ReportsModel) exportCmd() tea.Cmd { + entries := report.Entries(m.all, m.rng) + rng := m.rng + return func() tea.Msg { + path, err := exportCSV(entries, rng) + if errors.Is(err, errNoEntries) { + return ErrMsg("Nothing to export: no finished entries in this range") + } + if err != nil { + return ErrMsg("Export failed: " + err.Error()) + } + return StatusMsg(fmt.Sprintf("Exported %d %s to %s", len(entries), plural(len(entries), "entry", "entries"), tildePath(path))) + } +} + +// errNoEntries is exportCSV's answer for a range with nothing in it. +var errNoEntries = errors.New("no finished entries in this range") + +// exportCSV writes entries to a new file in exportDir named for the range, +// and returns its path. It never overwrites: when the name is taken it +// adds " (2)", " (3)"… before the extension. +func exportCSV(entries []*model.Entry, r report.Range) (string, error) { + if len(entries) == 0 { + return "", errNoEntries + } + dir, err := exportDir() + if err != nil { + return "", err + } + base := exportName(r) + for n := 1; n < 1000; n++ { + name := base + ".csv" + if n > 1 { + name = base + " (" + strconv.Itoa(n) + ").csv" + } + path := filepath.Join(dir, name) + // O_EXCL: fail rather than overwrite, even if another process + // makes the file between the check and the write. + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + if errors.Is(err, fs.ErrExist) { + continue + } + if err != nil { + return "", err + } + if err := report.WriteCSV(f, entries); err != nil { + f.Close() + os.Remove(path) + return "", err + } + if err := f.Close(); err != nil { + os.Remove(path) + return "", err + } + return path, nil + } + return "", fmt.Errorf("%s already has 999 exports named %s", tildePath(dir), base) +} + +// exportName is the file name for a range, without its extension: +// notch-2026-11-30-to-2026-12-03, notch-2026-12-03 for one day, +// notch-from-2026-11-30 or notch-to-2026-12-03 for an open side, and +// notch-all-time. +func exportName(r report.Range) string { + switch { + case r.From == "" && r.To == "": + return "notch-all-time" + case r.From == "": + return "notch-to-" + r.To + case r.To == "": + return "notch-from-" + r.From + case r.From == r.To: + return "notch-" + r.From + } + return "notch-" + r.From + "-to-" + r.To +} + +// exportDir is where exports go: the XDG download folder ($XDG_DOWNLOAD_DIR, +// or XDG_DOWNLOAD_DIR in user-dirs.dirs), else ~/Downloads, else the home +// folder, whichever exists first. +func exportDir() (string, error) { + home, homeErr := os.UserHomeDir() + var candidates []string + if d := os.Getenv("XDG_DOWNLOAD_DIR"); d != "" { + candidates = append(candidates, expandHome(d, home)) + } + if d := userDirsDownload(home); d != "" { + candidates = append(candidates, d) + } + if homeErr == nil { + candidates = append(candidates, filepath.Join(home, "Downloads"), home) + } + for _, d := range candidates { + if !filepath.IsAbs(d) { + continue + } + if fi, err := os.Stat(d); err == nil && fi.IsDir() { + return d, nil + } + } + if homeErr != nil { + return "", homeErr + } + return "", fmt.Errorf("no downloads or home folder to save to") +} + +// userDirsDownload reads XDG_DOWNLOAD_DIR from user-dirs.dirs in the XDG +// config folder, or "" if it isn't set there. +func userDirsDownload(home string) string { + cfg := os.Getenv("XDG_CONFIG_HOME") + if cfg == "" || !filepath.IsAbs(cfg) { + if home == "" { + return "" + } + cfg = filepath.Join(home, ".config") + } + f, err := os.Open(filepath.Join(cfg, "user-dirs.dirs")) + if err != nil { + return "" + } + defer f.Close() + sc := bufio.NewScanner(f) + for sc.Scan() { + k, v, ok := strings.Cut(strings.TrimSpace(sc.Text()), "=") + if !ok || strings.TrimSpace(k) != "XDG_DOWNLOAD_DIR" { + continue + } + return expandHome(strings.Trim(strings.TrimSpace(v), `"`), home) + } + return "" +} + +// expandHome replaces a leading $HOME or ~ with home. +func expandHome(p, home string) string { + if home == "" { + return p + } + for _, prefix := range []string{"$HOME", "${HOME}", "~"} { + if p == prefix || strings.HasPrefix(p, prefix+"/") { + return home + strings.TrimPrefix(p, prefix) + } + } + return p +} + +// tildePath shortens a path under the home folder to ~/…. +func tildePath(p string) string { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return p + } + if rel, err := filepath.Rel(home, p); err == nil && rel != ".." && !strings.HasPrefix(rel, "../") { + if rel == "." { + return "~" + } + return "~/" + rel + } + return p +} diff --git a/internal/ui/views/reports_test.go b/internal/ui/views/reports_test.go index b1137c9..756cbd6 100644 --- a/internal/ui/views/reports_test.go +++ b/internal/ui/views/reports_test.go @@ -1,485 +1,712 @@ package views import ( + "bytes" + "encoding/json" "fmt" + "os" + "path/filepath" + "regexp" "strings" "testing" "time" + "github.com/aliasproject/notch/internal/db" "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/report" + "github.com/aliasproject/notch/internal/theme" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/x/ansi" ) -func mkReportRow(clientName, projectName string, hours, earnings float64, entryCount, invoiced, paid int) *model.ReportRow { - return &model.ReportRow{ - ClientName: clientName, ProjectName: projectName, - TotalHours: hours, Earnings: earnings, - EntryCount: entryCount, Invoiced: invoiced, Paid: paid, - } -} - -// ── renderTotals / renderSummaryCards aggregation ──────────────────────────── - -func TestRenderTotals_SumsAcrossRows(t *testing.T) { - m := ReportsModel{width: 140, rows: []*model.ReportRow{ - mkReportRow("Acme", "Website", 2, 200, 2, 2, 1), - mkReportRow("Beta", "App", 3, 300, 3, 1, 0), - }} - - got := m.renderTotals() - if !strings.Contains(got, "5.00h") { - t.Errorf("renderTotals() should show total hours 5.00h, got: %q", got) - } - if !strings.Contains(got, "$500.00") { - t.Errorf("renderTotals() should show total earnings $500.00, got: %q", got) +// reportsNow is the sample's clock: Thursday 3 December 2026, 3 PM. +var reportsNow = time.Date(2026, 12, 3, 15, 0, 0, 0, time.Local) + +// seedReports fills d with the Reports board's sample week (Monday 30 +// November to today), one older entry this month, and a running timer. +func seedReports(t *testing.T, d *db.DB) { + t.Helper() + client := func(name string, rate float64) int64 { + c, err := d.CreateClient(name, rate) + if err != nil { + t.Fatal(err) + } + return c.ID } - if !strings.Contains(got, "3/5") { - t.Errorf("renderTotals() should show invoiced 3/5, got: %q", got) + project := func(clientID int64, name string) int64 { + p, err := d.CreateProject(clientID, name) + if err != nil { + t.Fatal(err) + } + return p.ID + } + harbor, field, internal := client("Harbor & Pine", 120), client("Fieldnote Studio", 95), client("Internal", 0) + web, booking := project(harbor, "Website rebuild"), project(harbor, "Booking app") + brand, notch := project(field, "Brand refresh"), project(internal, "notch") + add := func(pid int64, task string, day, hour, min, mins int, invoiced, paid bool) { + start := time.Date(2026, 11, day, hour, min, 0, 0, time.Local) // day 31 and up roll into December + end := start.Add(time.Duration(mins) * time.Minute) + e, err := d.AddEntry(pid, task, "", start, &end) + if err != nil { + t.Fatal(err) + } + if invoiced || paid { + e.Invoiced, e.Paid = invoiced, paid + if err := d.UpdateEntry(e); err != nil { + t.Fatal(err) + } + } } - if !strings.Contains(got, "1/5") { - t.Errorf("renderTotals() should show paid 1/5, got: %q", got) + add(web, "Kickoff", 20, 10, 0, 60, true, true) // Fri 20 Nov: this month, not this week + add(brand, "Moodboard review call", 30, 15, 0, 60, true, true) // Mon + add(notch, "Bar widget panel", 31, 10, 0, 130, false, false) // Tue 1 Dec + add(web, "Homepage hero and nav", 32, 9, 0, 105, true, false) // Wed + add(booking, "Calendar sync bug", 32, 13, 0, 200, true, false) // Wed + add(web, "Homepage hero and nav", 33, 9, 0, 105, false, false) // Thu + add(brand, "Logo explorations", 33, 11, 0, 90, false, false) // Thu + if _, err := d.AddEntry(web, "Pricing page layout", "", reportsNow.Add(-83*time.Minute), nil); err != nil { + t.Fatal(err) } } -func TestRenderSummaryCards_OutstandingExcludesFullyPaidRows(t *testing.T) { - // Row 1 is fully paid (Paid == EntryCount): its earnings should be excluded - // from "Outstanding". Row 2 is only partially paid, so its full earnings count. - m := ReportsModel{width: 140, rows: []*model.ReportRow{ - mkReportRow("Acme", "Website", 2, 200, 2, 2, 2), // fully paid - mkReportRow("Beta", "App", 3, 300, 3, 3, 1), // invoiced, partially paid - }} +// sampleReports is the Reports tab on the sample, at a content column +// w×h (as app.go's SetSize gives it), on This week. +func sampleReports(t *testing.T, w, h int) (ReportsModel, *db.DB) { + t.Helper() + d := newTestDB(t) + seedReports(t, d) + m := NewReports(d) + m.now = func() time.Time { return reportsNow } + m.SetSize(w, h) + m, _ = m.Update(m.loadCmd()()) + m, _ = m.Update(runeKey('w')) + return m, d +} - got := m.renderSummaryCards(5, 500, 5, 5, 3) - if !strings.Contains(got, "$300.00") { - t.Errorf("renderSummaryCards() Outstanding should be $300.00 (Beta's earnings only), got: %q", got) - } - // unpaidEntries = entries(5) - paid(3) = 2 - if !strings.Contains(got, "2 entries") { - t.Errorf("renderSummaryCards() Uninvoiced should show 2 entries, got: %q", got) +// press sends keys to m, running any command that loads the report. +func pressReports(m ReportsModel, keys ...tea.KeyMsg) ReportsModel { + for _, k := range keys { + var cmd tea.Cmd + m, cmd = m.Update(k) + if cmd == nil { + continue + } + if msg, ok := cmd().(reportEntriesMsg); ok { + m, _ = m.Update(msg) + } } + return m } -func TestRenderSummaryCards_NoRows(t *testing.T) { - m := ReportsModel{width: 140} - got := m.renderSummaryCards(0, 0, 0, 0, 0) - if !strings.Contains(got, "0.00 h") { - t.Errorf("renderSummaryCards() with no rows should show 0.00 h, got: %q", got) - } - if !strings.Contains(got, "$0.00") { - t.Errorf("renderSummaryCards() with no rows should show $0.00 earned, got: %q", got) +func typeKeys(s string) []tea.KeyMsg { + var out []tea.KeyMsg + for _, r := range s { + out = append(out, runeKey(r)) } + return out } -// ── mainColWidths ───────────────────────────────────────────────────────────── - -func TestMainColWidths_SpansAvailableWidth(t *testing.T) { - m := ReportsModel{width: 140} - clientW, projectW := m.mainColWidths() - if clientW <= 0 || projectW <= 0 { - t.Errorf("mainColWidths() = (%d, %d), want both positive", clientW, projectW) +func plainLines(s string) []string { return strings.Split(ansi.Strip(s), "\n") } + +// ── Range switching ─────────────────────────────────────────────────────────── + +func TestReports_RangeKeysSwitchToReportPresets(t *testing.T) { + m, _ := sampleReports(t, 140, 36) + for _, c := range []struct { + key rune + preset string + label string + }{ + {'t', "today", "Dec 3, 2026"}, + {'m', "month", "Dec 1 – Dec 3, 2026"}, + {'y', "year", "Jan 1 – Dec 3, 2026"}, + {'a', "all", "All time"}, + {'w', "week", "Nov 30 – Dec 3, 2026"}, + } { + m = pressReports(m, runeKey(c.key)) + want, _ := report.Preset(c.preset, reportsNow) + if string(m.preset) != c.preset || m.rng != want { + t.Errorf("%c: preset %q range %+v, want %q %+v", c.key, m.preset, m.rng, c.preset, want) + } + if m.rep.Range != want { + t.Errorf("%c: the report is for %+v, want %+v", c.key, m.rep.Range, want) + } + chips := plainLines(m.View())[0] + if !strings.Contains(chips, c.label) { + t.Errorf("%c: range line %q is missing %q", c.key, chips, c.label) + } } - total := usableWidth(140) - rColGutter - rColHours - rColEntries - rColInv - rColPaid - rColEarned - if clientW+projectW != total { - t.Errorf("clientW+projectW = %d, want %d (all remaining space used)", clientW+projectW, total) + // The on chip is the filled one, so it's not colour alone; its label is + // bold too. + if !strings.Contains(m.renderRangeChips(136), lipgloss.NewStyle().Foreground(cBg).Background(cPrimary).Bold(true).Render(" Week ")) { + t.Error("the Week chip should be filled while This week is on") } } -func TestMainColWidths_NeverNegative(t *testing.T) { - m := ReportsModel{width: 5} // far too narrow for even the fixed columns - clientW, projectW := m.mainColWidths() - if clientW < 0 || projectW < 0 { - t.Errorf("mainColWidths() = (%d, %d), want non-negative even at tiny widths", clientW, projectW) +func TestReports_CustomRangeModal(t *testing.T) { + m, _ := sampleReports(t, 140, 36) + m = pressReports(m, runeKey('f')) + if m.mode != reportsModeCustom || !m.IsBusy() { + t.Fatalf("f should open the custom range modal and capture keys, mode %v", m.mode) + } + if v := m.fromInput.Value(); v != "2026-11-30" { + t.Errorf("From opens on the current range's first day, got %q", v) + } + if !strings.Contains(plainLines(m.View())[0], "Custom range") && !strings.Contains(ansi.Strip(m.View()), "Custom range") { + t.Errorf("the modal should be titled Custom range:\n%s", ansi.Strip(m.View())) } -} -// ── View ────────────────────────────────────────────────────────────────────── + // q types in the field rather than quitting. + m.fromInput.SetValue("") + m = pressReports(m, typeKeys("q")...) + if m.fromInput.Value() != "q" { + t.Errorf("q should type into From, got %q", m.fromInput.Value()) + } + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if m.mode != reportsModeCustom || m.errs[customFieldFrom] != errCustomDate || m.FieldErrors() != 1 { + t.Fatalf("a bad date should stay open with an error under From, mode %v errs %v", m.mode, m.errs) + } + if !strings.Contains(ansi.Strip(m.View()), "✕ "+errCustomDate) { + t.Errorf("the error should show under its field:\n%s", ansi.Strip(m.View())) + } -// TestView_FilterModeHidesTable is a regression test: View() used to show -// the filter form *and* the (soon-to-be-stale) table underneath it at the -// same time, pushing the table down the page. It should now fully replace -// the body while filtering — just header + filter form — matching -// TimersModel.viewList's identical branch, and restore the table once -// filtering ends. -func TestView_FilterModeHidesTable(t *testing.T) { - m := NewReports(nil) - m.width, m.height = 100, 30 - m.rows = []*model.ReportRow{mkReportRow("Acme Corp", "Website Redesign", 2, 200, 2, 1, 0)} + // The last day before the first is an error on To. + m.fromInput.SetValue("2026-12-02") + m.toInput.SetValue("2026-12-01") + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if m.errs[customFieldTo] != errCustomOrder || m.focusIdx != customFieldTo { + t.Fatalf("To before From should be an error on To, errs %v focus %d", m.errs, m.focusIdx) + } - m.mode = reportsModeFilter - filtering := m.View() - if !strings.Contains(filtering, "From") || !strings.Contains(filtering, "To") { - t.Errorf("View() in filter mode should show the date-range filter bar, got:\n%s", filtering) + m.toInput.SetValue("2026-12-02") + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if m.mode != reportsModeView || m.preset != reportsPresetCustom || m.rng != (report.Range{From: "2026-12-02", To: "2026-12-02"}) { + t.Fatalf("enter should apply the range, mode %v preset %q rng %+v", m.mode, m.preset, m.rng) } - // "Website Redesign" gets column-truncated to "Website Red…" in the - // table, so check for a prefix that survives that rather than the full - // name. - if strings.Contains(filtering, "Acme Corp") || strings.Contains(filtering, "Website Red") { - t.Errorf("View() in filter mode should hide the table, not push it down below the filter bar, got:\n%s", filtering) + if m.rep.Entries != 2 { + t.Errorf("Wed 2 Dec has 2 finished entries, report has %d", m.rep.Entries) } - m.mode = reportsModeView - normal := m.View() - if !strings.Contains(normal, "Acme Corp") || !strings.Contains(normal, "Website Red") { - t.Errorf("View() outside filter mode should show the table again, got:\n%s", normal) + // esc leaves the range alone; blank dates open both sides. + m = pressReports(m, runeKey('f')) + m.fromInput.SetValue("") + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEsc}) + if m.mode != reportsModeView || m.rng.From != "2026-12-02" { + t.Errorf("esc should cancel, rng %+v", m.rng) + } + m = pressReports(m, runeKey('f')) + m.fromInput.SetValue("") + m.toInput.SetValue("") + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if m.rng != (report.Range{}) || !strings.Contains(plainLines(m.View())[0], "All time") { + t.Errorf("blank dates should mean all time, rng %+v", m.rng) } } -// ── Filter-mode transitions ────────────────────────────────────────────────── +// ── Numbers ─────────────────────────────────────────────────────────────────── -func TestReportsUpdateView_FilterKeyEntersFilterMode(t *testing.T) { - m := NewReports(nil) - got, cmd := m.updateView(runeKey('f')) - if got.mode != reportsModeFilter { - t.Errorf("mode after 'f' = %v, want reportsModeFilter", got.mode) +// The tab's numbers are report.Build's for the range, as "notch report +// -json" prints them: same entries (the CLI lists them without the running +// one), same range, same JSON. +func TestReports_NumbersMatchReportJSON(t *testing.T) { + m, d := sampleReports(t, 140, 36) + cliEntries, err := d.ListEntries(0, "", "", false) + if err != nil { + t.Fatal(err) } - if cmd == nil { - t.Error("want a non-nil cmd (textinput.Blink) after entering filter mode") + for _, k := range []rune{'t', 'w', 'm', 'y', 'a'} { + m = pressReports(m, runeKey(k)) + want, _ := json.Marshal(report.Build(cliEntries, m.rng)) + got, _ := json.Marshal(m.rep) + if !bytes.Equal(got, want) { + t.Errorf("%c: the tab's report differs from notch report -json:\n got %s\nwant %s", k, got, want) + } } } -func TestReportsUpdateFilter_ApplyCommitsDates(t *testing.T) { - m := NewReports(nil) - m.mode = reportsModeFilter - m.fromInput.SetValue("2024-01-01") - m.toInput.SetValue("2024-01-31") - - got, cmd := m.updateFilter(tea.KeyMsg{Type: tea.KeyEnter}) - if got.mode != reportsModeView { - t.Errorf("mode after apply = %v, want reportsModeView", got.mode) +func TestReports_StatCardsShowTheReport(t *testing.T) { + m, _ := sampleReports(t, 140, 36) + view := ansi.Strip(m.View()) + // This week on the board's sample: 11:30:00 over six entries, $1,057.50 + // earned, $610.00 invoiced and not paid, $352.50 over three entries not + // invoiced. The running timer isn't counted. + for _, want := range []string{ + "HOURS", "11:30:00", "6 entries", + "EARNED", "$1,057.50", "avg $91.96/h", + "OUTSTANDING", "$610.00", "invoiced, not paid", + "UNBILLED", "$352.50", "3 entries", + "Running timer not counted until it stops.", + } { + if !strings.Contains(view, want) { + t.Errorf("the cards are missing %q:\n%s", want, view) + } } - if got.dateFrom != "2024-01-01" || got.dateTo != "2024-01-31" { - t.Errorf("dateFrom/dateTo = %q/%q, want 2024-01-01/2024-01-31", got.dateFrom, got.dateTo) + rep := m.rep + if rep.Seconds != 690*60 || rep.Earned != 1057.5 || rep.Outstanding != 610 || rep.Unbilled != 352.5 || rep.UnbilledEntries != 3 { + t.Errorf("report %+v", rep) } - if cmd == nil { - t.Error("want a non-nil loadCmd after applying the filter") + // Each card's value is the report's, formatted. + cards := m.statCards() + for i, want := range []string{model.FormatDuration(time.Duration(rep.Seconds) * time.Second), formatMoney(rep.Earned), formatMoney(rep.Outstanding), formatMoney(rep.Unbilled)} { + if cards[i].value != want { + t.Errorf("card %s = %q, want %q", cards[i].label, cards[i].value, want) + } } } -func TestReportsUpdateFilter_EscCancelsWithoutCommitting(t *testing.T) { - m := NewReports(nil) - m.mode = reportsModeFilter - m.dateFrom, m.dateTo = "2024-06-01", "2024-06-30" - m.fromInput.SetValue("garbage") +// ── Bars ────────────────────────────────────────────────────────────────────── - got, cmd := m.updateFilter(tea.KeyMsg{Type: tea.KeyEsc}) - if got.mode != reportsModeView { - t.Errorf("mode after esc = %v, want reportsModeView", got.mode) +func TestReports_BarsByDay(t *testing.T) { + m, _ := sampleReports(t, 140, 36) + bars, slot, barW := chartBars(m.rep.Days, 64, "2026-12-03") + if len(bars) != 4 || slot != theme.BarWidth+theme.BarGap || barW != theme.BarWidth { + t.Fatalf("a week to Thursday is four day bars %d wide in %d, got %d bars %d in %d", theme.BarWidth, slot, len(bars), barW, slot) } - if got.dateFrom != "2024-06-01" || got.dateTo != "2024-06-30" { - t.Errorf("dates should be untouched on cancel, got %q/%q", got.dateFrom, got.dateTo) + var labels, hours []string + for _, b := range bars { + labels = append(labels, b.label) + hours = append(hours, hoursLabel(b.secs)) } - if cmd != nil { - t.Error("want nil cmd on cancel") + if got := strings.Join(labels, " "); got != "Mon Tue Wed Thu" { + t.Errorf("labels %q", got) + } + if got := strings.Join(hours, " "); got != "1.0h 2.2h 5.1h 3.2h" { + t.Errorf("hours %q", got) + } + if !bars[3].today || bars[0].today { + t.Error("only Thursday is today") } -} - -func TestReportsUpdateFilter_TabTogglesFocus(t *testing.T) { - m := NewReports(nil) - m.mode = reportsModeFilter - m.filterIdx = 0 - got, _ := m.updateFilter(tea.KeyMsg{Type: tea.KeyTab}) - if got.filterIdx != 1 { - t.Errorf("filterIdx after tab = %d, want 1", got.filterIdx) + lines := m.renderBars(66, theme.BarRows, reportsNow) + if len(lines) != barsRows(theme.BarRows) { + t.Fatalf("%d lines, want %d", len(lines), barsRows(theme.BarRows)) + } + plain := make([]string, len(lines)) + for i, l := range lines { + plain[i] = ansi.Strip(l) + if w := lipgloss.Width(l); w != 66 { + t.Errorf("line %d is %d wide", i, w) + } + } + // Wednesday, the most, fills every row; Monday, a fifth of it, only the + // bottom one; the days and hours are written under the bars. + col := func(i int) int { return theme.Gutter + i*(theme.BarWidth+theme.BarGap) } + for r := 1; r <= theme.BarRows; r++ { + if got := []rune(plain[r])[col(2)]; got != '█' { + t.Errorf("Wednesday's row %d is %q, want a full block", r, got) + } + } + if got := []rune(plain[1])[col(0)]; got != ' ' { + t.Errorf("Monday's top row should be empty, got %q", got) + } + // This week's bars run on to Sunday, empty. + if !strings.Contains(plain[theme.BarRows+1], "Mon Tue Wed Thu Fri Sat Sun") || !strings.Contains(plain[theme.BarRows+2], "1.0h 2.2h 5.1h 3.2h — — —") { + t.Errorf("labels:\n%s\n%s", plain[theme.BarRows+1], plain[theme.BarRows+2]) + } + // Today's name is bold, so it isn't marked by the bar's colour alone. + if !strings.Contains(lines[theme.BarRows+1], lipgloss.NewStyle().Foreground(cText).Background(cBg).Bold(true).Render(fit("Thu", theme.BarWidth+theme.BarGap))) { + t.Error("today's day name should be bold") } +} - got2, _ := got.updateFilter(tea.KeyMsg{Type: tea.KeyShiftTab}) - if got2.filterIdx != 0 { - t.Errorf("filterIdx after shift+tab = %d, want back to 0", got2.filterIdx) +func TestReports_BarsGroupLongRanges(t *testing.T) { + days := func(from, to string) []report.Day { + a, _ := time.ParseInLocation("2006-01-02", from, time.Local) + b, _ := time.ParseInLocation("2006-01-02", to, time.Local) + var out []report.Day + for d := a; !d.After(b); d = d.AddDate(0, 0, 1) { + out = append(out, report.Day{Date: d.Format("2006-01-02"), Seconds: 3600}) + } + return out + } + for _, c := range []struct { + name, from, to string + w int + first, last string + n int + }{ + {"a month is weeks", "2026-12-01", "2026-12-31", 66, "Dec 1", "Dec 28", 5}, + {"a year is months", "2026-01-01", "2026-12-31", 66, "Jan", "Dec", 12}, + {"years are years", "2023-03-01", "2026-12-03", 66, "2023", "2026", 4}, + {"a week fits by day in narrow bars", "2026-02-01", "2026-02-07", 40, "Sun", "Sat", 7}, + {"but not in too little room", "2026-02-01", "2026-02-07", 30, "Feb 1", "Feb 2", 2}, + } { + bars, slot, _ := chartBars(days(c.from, c.to), c.w, "") + if len(bars) != c.n || bars[0].label != c.first || bars[len(bars)-1].label != c.last { + var got []string + for _, b := range bars { + got = append(got, b.label) + } + t.Errorf("%s: got %v", c.name, got) + continue + } + if len(bars)*slot > c.w { + t.Errorf("%s: %d bars of %d don't fit %d", c.name, len(bars), slot, c.w) + } + for _, b := range bars { + if lipgloss.Width(b.label) >= slot || lipgloss.Width(hoursLabel(b.secs)) >= slot { + t.Errorf("%s: %q / %q don't fit a slot of %d", c.name, b.label, hoursLabel(b.secs), slot) + } + } } } -// ── Preset keys (each issues a reload cmd) ─────────────────────────────────── +// ── Table ───────────────────────────────────────────────────────────────────── -func TestReportsUpdateView_PresetKeysSetDateRange(t *testing.T) { - m := NewReports(nil) +// reportRowRE finds a table row: its name, then hours, invoiced, paid and +// earned. +var reportRowRE = regexp.MustCompile(`(\S.*?)\s{2,}(\d+:\d\d:\d\d)\s+(\d+/\d+)\s+(\d+/\d+)\s+(\S+)\s*$`) - got, cmd := m.updateView(runeKey('a')) // "all time" - if got.dateFrom != "" || got.dateTo != "" { - t.Errorf("dateFrom/dateTo after 'a' = %q/%q, want both empty", got.dateFrom, got.dateTo) - } - if cmd == nil { - t.Error("want a non-nil loadCmd after changing the preset") - } +func TestReports_NestedTableAt140And90(t *testing.T) { + for _, size := range [][2]int{{140, 36}, {90, 28}} { + w, h := size[0], size[1] + m, _ := sampleReports(t, w, h) + view := m.View() + lines := plainLines(view) + if len(lines) > h-2 { + t.Errorf("%d: %d lines, more than the %d rows inside the padding", w, len(lines), h-2) + } + for i, l := range strings.Split(view, "\n") { + if lw := lipgloss.Width(l); lw != w-2*theme.Margin { + t.Errorf("%d: line %d is %d wide, want %d: %q", w, i, lw, w-2*theme.Margin, ansi.Strip(l)) + } + } + + want := []struct{ name, hours, inv, paid, earned string }{ + {"Fieldnote Studio", "2:30:00", "1/2", "1/2", "$237.50"}, + {" Brand refresh", "2:30:00", "1/2", "1/2", "$237.50"}, + {"Harbor & Pine", "6:50:00", "2/3", "0/3", "$820.00"}, + {" Booking app", "3:20:00", "1/1", "0/1", "$400.00"}, + {" Website rebuild", "3:30:00", "1/2", "0/2", "$420.00"}, + {"Internal", "2:10:00", "0/1", "0/1", "—"}, + {" notch", "2:10:00", "0/1", "0/1", "—"}, + {"Total", "11:30:00", "3/6", "1/6", "$1,057.50"}, + } + var rows []string + tableCol := 0 + for _, l := range lines { + if i := strings.Index(l, "BY CLIENT AND PROJECT"); i >= 0 { + tableCol = len([]rune(l[:i])) + } + } + for _, l := range lines { + r := []rune(l) + if len(r) < tableCol { + continue + } + if g := reportRowRE.FindStringSubmatch(string(r[tableCol:])); g != nil { + rows = append(rows, strings.Join(g[1:], "|")) + } + } + if len(rows) != len(want) { + t.Fatalf("%d: table rows:\n%s\n\nview:\n%s", w, strings.Join(rows, "\n"), strings.Join(lines, "\n")) + } + for i, r := range want { + // The cursor's ▌ starts the first row. + name := strings.Repeat(" ", theme.Gutter-1) + r.name + if i == 0 { + name = theme.GlyphCursor + name[1:] + } + if got, w := rows[i], strings.Join([]string{strings.TrimSpace(name), r.hours, r.inv, r.paid, r.earned}, "|"); strings.TrimLeft(got, theme.GlyphCursor+" ") != strings.TrimLeft(w, theme.GlyphCursor+" ") { + t.Errorf("row %d = %q, want %q", i, got, w) + } + } + // Projects sit tui-report-indent in from their client. + var clientAt, projectAt int + for _, l := range lines { + if i := strings.Index(l, "Harbor & Pine"); i >= 0 { + clientAt = len([]rune(l[:i])) + } + if i := strings.Index(l, "Booking app"); i >= 0 && !strings.Contains(l, "Calendar") { + projectAt = len([]rune(l[:i])) + } + } + if projectAt-clientAt != theme.ReportIndent { + t.Errorf("%d: project at %d, client at %d, want %d in", w, projectAt, clientAt, theme.ReportIndent) + } - got2, _ := m.updateView(runeKey('t')) // "today" - if got2.dateFrom == "" || got2.dateFrom != got2.dateTo { - t.Errorf("dateFrom/dateTo after 't' = %q/%q, want equal non-empty dates", got2.dateFrom, got2.dateTo) + // Wide: the bars beside the table. Narrow: above it. + byDay, byClient := -1, -1 + for i, l := range lines { + if strings.Contains(l, "BY DAY") { + byDay = i + } + if strings.Contains(l, "BY CLIENT AND PROJECT") { + byClient = i + } + } + if w >= theme.WideMin && byDay != byClient { + t.Errorf("%d: the bars should sit beside the table:\n%s", w, strings.Join(lines, "\n")) + } + if w < theme.WideMin && !(byDay >= 0 && byDay < byClient) { + t.Errorf("%d: the bars should sit above the table:\n%s", w, strings.Join(lines, "\n")) + } + if dir := os.Getenv("NOTCH_RENDER_DIR"); dir != "" { + os.WriteFile(filepath.Join(dir, fmt.Sprintf("ali-2618-reports-%d.txt", w)), []byte(strings.Join(lines, "\n")+"\n"), 0o644) + } } } -// ── Help ────────────────────────────────────────────────────────────────────── - -// TestHelp_MentionsDrillDown is a regression test for a discoverability -// gap: View() always shows the selected row's underlying entries below the -// table (no dedicated key — it's automatic, driven by cursor position, see -// the "Drill-down" comment in View()), but the old hotkey text just said -// "↑/↓ navigate", giving no hint that navigating also reveals that. It -// should call out what up/down actually does here, not just that they move -// the cursor. -func TestHelp_MentionsDrillDown(t *testing.T) { - m := ReportsModel{mode: reportsModeView} - got := m.Help() - found := false - for _, h := range got { - if strings.Contains(h.Label, "entries") { - found = true - break - } +// A short terminal drops the bars before the table gets fewer than +// minReportRows rows, and scrolls the table to keep the cursor in view. +func TestReports_ShortTerminalKeepsTableRows(t *testing.T) { + m, _ := sampleReports(t, 90, 18) + if m.compactChartRows() != 0 || strings.Contains(ansi.Strip(m.View()), "BY DAY") { + t.Errorf("at 90×18 the bars should go:\n%s", ansi.Strip(m.View())) + } + if m.rowsBudget() < minReportRows { + t.Errorf("rows budget %d", m.rowsBudget()) } - if !found { - t.Errorf("Help() = %v, want it to mention that ↑/↓ reveals the row's entries", got) + if n := len(plainLines(m.View())); n > 16 { + t.Errorf("%d lines in 16 rows", n) + } + for i := 0; i < len(m.lines); i++ { + m = pressReports(m, runeKey('j')) + if !strings.Contains(ansi.Strip(m.View()), theme.GlyphCursor) { + t.Fatalf("cursor on row %d is off screen", m.cursor) + } } } -// ── loadCmd / entries drill-down ───────────────────────────────────────────── +// ── Export ──────────────────────────────────────────────────────────────────── -// TestLoadCmd_PopulatesEntries is a regression test: ReportByProject only -// aggregates (SUM/COUNT via GROUP BY) — it never attached the underlying -// entries, so renderEntries' drill-down had nothing to show for any row, -// no matter how you navigated. loadCmd should now fetch and attach each -// row's entries itself. -func TestLoadCmd_PopulatesEntries(t *testing.T) { - d := newTestDB(t) - c, err := d.CreateClient("Acme", 100) - if err != nil { - t.Fatal(err) +func TestReports_ExportCSV(t *testing.T) { + dir := t.TempDir() + t.Setenv("XDG_DOWNLOAD_DIR", dir) + m, _ := sampleReports(t, 140, 36) + + m, cmd := m.Update(runeKey('e')) + if cmd == nil || m.IsBusy() { + t.Fatal("e should export without opening anything") } - p, err := d.CreateProject(c.ID, "Website") - if err != nil { - t.Fatal(err) + msg, ok := cmd().(StatusMsg) + path := filepath.Join(dir, "notch-2026-11-30-to-2026-12-03.csv") + if !ok || !strings.Contains(string(msg), "Exported 6 entries to ") || !strings.HasSuffix(string(msg), "notch-2026-11-30-to-2026-12-03.csv") { + t.Fatalf("status %T %q", msg, msg) } - e, err := d.StartEntry(p.ID, "build feature") + got, err := os.ReadFile(path) if err != nil { t.Fatal(err) } - if err := d.StopEntry(e.ID); err != nil { + var want bytes.Buffer + if err := report.WriteCSV(&want, report.Entries(m.all, m.rng)); err != nil { t.Fatal(err) } - - m := ReportsModel{db: d} - msg := m.loadCmd()() - rows, ok := msg.(reportRowsMsg) - if !ok { - t.Fatalf("loadCmd() produced %T, want reportRowsMsg", msg) + if !bytes.Equal(got, want.Bytes()) { + t.Errorf("the file isn't report.WriteCSV's:\n%s\nwant:\n%s", got, want.String()) } - if len(rows) != 1 { - t.Fatalf("len(rows) = %d, want 1", len(rows)) + if n := strings.Count(string(got), "\n"); n != 7 { + t.Errorf("%d lines, want the header and six entries", n) + } + + // Again: a new file, the first one kept. + if err := os.WriteFile(path, []byte("keep me"), 0o644); err != nil { + t.Fatal(err) } - if len(rows[0].Entries) != 1 { - t.Fatalf("rows[0].Entries = %+v, want 1 entry", rows[0].Entries) + msg2 := m.exportCmd()().(StatusMsg) + if !strings.HasSuffix(string(msg2), "notch-2026-11-30-to-2026-12-03 (2).csv") { + t.Errorf("second export: %q", msg2) } - if rows[0].Entries[0].Task != "build feature" { - t.Errorf("rows[0].Entries[0].Task = %q, want %q", rows[0].Entries[0].Task, "build feature") + if b, _ := os.ReadFile(path); string(b) != "keep me" { + t.Error("the second export overwrote the first") } -} -func TestLoadCmd_Error(t *testing.T) { - d := newTestDB(t) - d.Close() - m := ReportsModel{db: d} - msg := m.loadCmd()() - if _, ok := msg.(ErrMsg); !ok { - t.Errorf("loadCmd() on a closed db produced %T, want ErrMsg", msg) + // A range with nothing in it says so and writes nothing. + m = pressReports(m, runeKey('f')) + m.fromInput.SetValue("2020-01-01") + m.toInput.SetValue("2020-01-02") + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if e, ok := m.exportCmd()().(ErrMsg); !ok || !strings.Contains(string(e), "Nothing to export") { + t.Errorf("empty export: %v", e) + } + if files, _ := os.ReadDir(dir); len(files) != 2 { + t.Errorf("%d files, want 2", len(files)) } } -// ── Table windowing ─────────────────────────────────────────────────────────── - -// TestClampOffset_Reports_ScrollsSelectedRowIntoView checks that a report -// with many client/project rows scrolls the table (rather than overflowing -// the screen) to keep the selected row visible — mirroring -// TimersModel.viewList's identical windowing for its own list. -func TestClampOffset_Reports_ScrollsSelectedRowIntoView(t *testing.T) { - var rows []*model.ReportRow - for i := 0; i < 20; i++ { - rows = append(rows, mkReportRow("Acme", fmt.Sprintf("Project %02d", i), 1, 0, 1, 0, 0)) +func TestReports_ExportNamesAndFolder(t *testing.T) { + for r, want := range map[report.Range]string{ + {}: "notch-all-time", + {From: "2026-12-03", To: "2026-12-03"}: "notch-2026-12-03", + {From: "2026-12-01"}: "notch-from-2026-12-01", + {To: "2026-12-03"}: "notch-to-2026-12-03", + } { + if got := exportName(r); got != want { + t.Errorf("exportName(%+v) = %q, want %q", r, got, want) + } } - m := ReportsModel{width: 120, height: 20, rows: rows, cursor: 19} - m.clampOffset() - - budget := m.rowsBudget() - if budget < 1 { - t.Fatalf("rowsBudget() = %d, want >= 1", budget) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_DOWNLOAD_DIR", "") + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + if d, _ := exportDir(); d != home { + t.Errorf("with no Downloads, exports go home: %q", d) + } + os.Mkdir(filepath.Join(home, "Downloads"), 0o755) + if d, _ := exportDir(); d != filepath.Join(home, "Downloads") { + t.Errorf("~/Downloads: %q", d) } - if m.cursor < m.offset || m.cursor >= m.offset+budget { - t.Errorf("cursor %d not within visible window [%d, %d) after clampOffset", m.cursor, m.offset, m.offset+budget) + os.MkdirAll(filepath.Join(home, ".config"), 0o755) + os.Mkdir(filepath.Join(home, "Téléchargements"), 0o755) + os.WriteFile(filepath.Join(home, ".config", "user-dirs.dirs"), []byte("# xdg\nXDG_DOWNLOAD_DIR=\"$HOME/Téléchargements\"\n"), 0o644) + if d, _ := exportDir(); d != filepath.Join(home, "Téléchargements") { + t.Errorf("user-dirs.dirs: %q", d) + } + if got := tildePath(filepath.Join(home, "Downloads", "x.csv")); got != "~/Downloads/x.csv" { + t.Errorf("tildePath = %q", got) } } -// ── Entries mode: transitions ───────────────────────────────────────────────── +// ── Enter: the entries behind a row ─────────────────────────────────────────── -func TestUpdateView_EnterOpensEntriesMode(t *testing.T) { - rows := []*model.ReportRow{mkReportRow("Acme", "Web", 1, 100, 1, 0, 0)} - m := ReportsModel{mode: reportsModeView, rows: rows, cursor: 0, entriesOffset: 3} +func TestReports_EnterShowsTheRowsEntries(t *testing.T) { + m, _ := sampleReports(t, 140, 36) + tasks := func(es []*model.Entry) string { + var out []string + for _, e := range es { + out = append(out, e.Task) + } + return strings.Join(out, ", ") + } - got, _ := m.updateView(tea.KeyMsg{Type: tea.KeyEnter}) - if got.mode != reportsModeEntries { - t.Errorf("mode after enter = %v, want reportsModeEntries", got.mode) + // Harbor & Pine is the third row (after Fieldnote Studio and its + // project): all its entries this week, newest first. + m = pressReports(m, runeKey('j'), runeKey('j')) + if l := m.selectedLine(); l == nil || l.name != "Harbor & Pine" { + t.Fatalf("selected %+v", l) } - if got.entriesOffset != 0 { - t.Errorf("entriesOffset after opening = %d, want reset to 0", got.entriesOffset) + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if m.mode != reportsModeEntries || !m.IsBusy() { + t.Fatalf("enter should open the entries, mode %v", m.mode) } -} - -func TestUpdateView_EnterWithNoRowsIsNoOp(t *testing.T) { - m := ReportsModel{mode: reportsModeView} - got, _ := m.updateView(tea.KeyMsg{Type: tea.KeyEnter}) - if got.mode != reportsModeView { - t.Errorf("mode after enter with no rows = %v, want to stay reportsModeView", got.mode) + if got := tasks(m.selectedEntries()); got != "Homepage hero and nav, Calendar sync bug, Homepage hero and nav" { + t.Errorf("Harbor & Pine's entries: %s", got) } -} - -func TestUpdateEntries_EscGoesBack(t *testing.T) { - m := ReportsModel{mode: reportsModeEntries} - got, _ := m.updateEntries(tea.KeyMsg{Type: tea.KeyEsc}) - if got.mode != reportsModeView { - t.Errorf("mode after esc = %v, want reportsModeView", got.mode) + view := ansi.Strip(m.View()) + if !strings.Contains(view, "Harbor & Pine · 6:50:00 · $820.00") || !strings.Contains(view, "Calendar sync bug") { + t.Errorf("entries view:\n%s", view) } -} -func TestUpdateEntries_ScrollsWithinBounds(t *testing.T) { - c := mkClient(1, "Acme", 100) - p := mkProject(1, "Web", c) - r := mkReportRow("Acme", "Web", 1, 100, 10, 0, 0) - for i := 0; i < 10; i++ { - r.Entries = append(r.Entries, mkEntry(int64(i+1), p, "t", time.Now(), 10)) + // A project row: only its entries. + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEsc}, runeKey('j')) + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if got := tasks(m.selectedEntries()); got != "Calendar sync bug" { + t.Errorf("Booking app's entries: %s", got) } - m := ReportsModel{mode: reportsModeEntries, width: 120, height: 15, rows: []*model.ReportRow{r}, cursor: 0} - - // Up at offset 0 stays at 0 (no underflow). - got, _ := m.updateEntries(runeKey('k')) - if got.entriesOffset != 0 { - t.Errorf("entriesOffset after up at 0 = %d, want 0", got.entriesOffset) + if !strings.Contains(ansi.Strip(m.View()), "Harbor & Pine › Booking app") { + t.Errorf("project title:\n%s", ansi.Strip(m.View())) } - // Down repeatedly must not exceed what clampEntriesOffset allows. - for i := 0; i < 20; i++ { - got, _ = got.updateEntries(runeKey('j')) + // e edits the selected entry there. + m, cmd := m.Update(runeKey('e')) + if cmd == nil { + t.Fatal("e should load the edit form") } - budget := got.entriesRowsBudget() - maxOffset := len(r.Entries) - budget - if maxOffset < 0 { - maxOffset = 0 + m, _ = m.Update(cmd()) + if m.mode != reportsModeEditEntry || m.editForm.inputs[0].Value() != "Calendar sync bug" { + t.Fatalf("edit form: mode %v task %q", m.mode, m.editForm.inputs[0].Value()) } - if got.entriesOffset > maxOffset { - t.Errorf("entriesOffset = %d after scrolling past the end, want clamped to <= %d", got.entriesOffset, maxOffset) + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + if m.mode != reportsModeEntries { + t.Errorf("esc should close the form back to the entries, mode %v", m.mode) } } -// ── renderEntriesView ──────────────────────────────────────────────────────── - -// TestRenderEntriesView_AllEntriesReachableByScrolling is a regression test -// replacing the old capped inline drill-down: with many entries and a -// short view, not everything fits in one screen, but every entry should -// still be reachable by scrolling (via entriesOffset) rather than -// permanently truncated behind a "… and N more" note with no way to see -// the rest. -func TestRenderEntriesView_AllEntriesReachableByScrolling(t *testing.T) { - c := mkClient(1, "Acme", 100) - p := mkProject(1, "Web", c) - base := time.Date(2024, 5, 1, 9, 0, 0, 0, time.Local) +func TestReports_EnterWithNoRowsIsNoOp(t *testing.T) { + m := ReportsModel{mode: reportsModeView} + got, _ := m.updateView(tea.KeyMsg{Type: tea.KeyEnter}) + if got.mode != reportsModeView { + t.Errorf("mode after enter with no rows = %v, want to stay reportsModeView", got.mode) + } +} - r := &model.ReportRow{ClientName: "Acme", ProjectName: "Web", HourlyRate: 100} +func TestReports_EntriesScrollAndEveryEntryIsReachable(t *testing.T) { + d := newTestDB(t) + c, _ := d.CreateClient("Acme", 100) + p, _ := d.CreateProject(c.ID, "Web") + base := time.Date(2024, 5, 1, 9, 0, 0, 0, time.Local) const total = 15 for i := 0; i < total; i++ { - r.Entries = append(r.Entries, mkEntry(int64(i+1), p, fmt.Sprintf("task %d", i), base.Add(time.Duration(i)*time.Hour), 10)) + start := base.Add(time.Duration(i) * time.Hour) + end := start.Add(10 * time.Minute) + if _, err := d.AddEntry(p.ID, fmt.Sprintf("task %d", i), "", start, &end); err != nil { + t.Fatal(err) + } } - - m := ReportsModel{width: 120, height: 15, rows: []*model.ReportRow{r}, cursor: 0} - budget := m.entriesRowsBudget() - if budget >= total { - t.Fatalf("test setup invalid: budget %d must be smaller than %d entries to exercise scrolling", budget, total) + m := NewReports(d) + m.SetSize(120, 15) + m, _ = m.Update(m.loadCmd()()) + m = pressReports(m, runeKey('a'), tea.KeyMsg{Type: tea.KeyEnter}) + if m.mode != reportsModeEntries { + t.Fatalf("mode %v", m.mode) + } + if m.entriesRowsBudget() >= total { + t.Fatalf("budget %d must be smaller than %d entries", m.entriesRowsBudget(), total) } - seen := map[string]bool{} - for m.entriesCursor = 0; m.entriesCursor < total; m.entriesCursor++ { - m.clampEntriesOffset() - got := m.renderEntriesView() - for i := 0; i < total; i++ { - task := fmt.Sprintf("task %d", i) - if strings.Contains(got, task) { - seen[task] = true + for i := 0; i < total+3; i++ { + view := m.View() + for j := 0; j < total; j++ { + if strings.Contains(view, fmt.Sprintf("task %d", j)) { + seen[fmt.Sprintf("task %d", j)] = true } } + m = pressReports(m, runeKey('j')) } if len(seen) != total { - t.Errorf("scrolled through every entry but only saw %d/%d distinct tasks", len(seen), total) + t.Errorf("saw %d of %d entries", len(seen), total) } -} - -func TestRenderEntriesView_NoEntries(t *testing.T) { - r := &model.ReportRow{ClientName: "Acme", ProjectName: "Web"} - m := ReportsModel{width: 120, height: 20, rows: []*model.ReportRow{r}, cursor: 0} - got := m.renderEntriesView() - if !strings.Contains(got, "No entries") { - t.Errorf("renderEntriesView with no entries = %q, want it to say so", got) + if max := total - m.entriesRowsBudget(); m.entriesOffset > max { + t.Errorf("entriesOffset %d past %d", m.entriesOffset, max) } } -func TestRenderEntriesView_NoSelection(t *testing.T) { - m := ReportsModel{width: 120, height: 20} - got := m.renderEntriesView() - if got == "" { - t.Error("renderEntriesView with no selection should still render (falls back to the header), got empty string") - } -} +// ── Modes, keys and loading ─────────────────────────────────────────────────── -// TestEntryCols_RowWidthMatchesDivider is a regression test: entryCols used -// to subtract a hardcoded 8 for the status column's width instead of the -// actual 12, leaving every entry row (and the table header) 4 columns wider -// than totalW/the divider. Since app.go's outer column wraps the whole view -// in Width(cw), and lipgloss word-wraps (never truncates) content wider -// than that, every over-width row silently wrapped onto an extra line — -// doubling the effective table height, overflowing well past -// entriesRowsBudget, and pushing the header off the top of the screen in a -// real terminal (a headless string-only render doesn't show this, since -// nothing there re-wraps the way the live app's outer Width(cw) does). -func TestEntryCols_RowWidthMatchesDivider(t *testing.T) { - for _, w := range []int{80, 100, 120, 150, 200} { - m := ReportsModel{width: w} - date, task, dur, earned, status := m.entryCols() - gotRowWidth := 2 + date + task + dur + earned + status // 2 = RowPrefix gutter - wantRowWidth := usableWidth(w) - if gotRowWidth != wantRowWidth { - t.Errorf("width=%d: entry row width = %d, want exactly %d (usableWidth) — any mismatch triggers unwanted word-wrap", w, gotRowWidth, wantRowWidth) +func TestReports_HelpAndBusyByMode(t *testing.T) { + keys := func(hs []Hotkey) string { + var out []string + for _, h := range hs { + out = append(out, h.Key+" "+h.Label) } + return strings.Join(out, ", ") } -} - -func TestView_EntriesMode(t *testing.T) { - rows := []*model.ReportRow{mkReportRow("Acme", "Web", 1, 100, 1, 0, 0)} - rows[0].Entries = []*model.Entry{mkEntry(1, mkProject(1, "Web", mkClient(1, "Acme", 100)), "build feature", time.Now(), 30)} - - m := ReportsModel{mode: reportsModeEntries, width: 120, height: 20, rows: rows, cursor: 0} - got := m.View() - if !strings.Contains(got, "Acme › Web") { - t.Errorf("View() in entries mode should show the selected row's title, got:\n%s", got) + m := ReportsModel{} + if got := keys(m.Help()); got != "t today, w week, m month, f custom, e export CSV, ↵ entries" || m.IsBusy() { + t.Errorf("report keys %q busy %v", got, m.IsBusy()) + } + for _, mode := range []reportsMode{reportsModeCustom, reportsModeEntries, reportsModeEditEntry} { + m.mode = mode + if !m.IsBusy() { + t.Errorf("mode %v should capture keys", mode) + } } - if !strings.Contains(got, "build feature") { - t.Errorf("View() in entries mode should show its entries, got:\n%s", got) + m.mode = reportsModeEntries + if got := keys(m.Help()); !strings.Contains(got, "esc back") || !strings.Contains(got, "e edit") { + t.Errorf("entries keys %q", got) } } -func TestHelp_EntriesMode(t *testing.T) { - m := ReportsModel{mode: reportsModeEntries} - got := m.Help() - found := false - for _, h := range got { - if h.Key == "esc" { - found = true - break - } - } - if !found { - t.Errorf("Help() in entries mode = %v, want it to mention esc to go back", got) +func TestReports_LoadCmdError(t *testing.T) { + d := newTestDB(t) + d.Close() + m := ReportsModel{db: d} + if _, ok := m.loadCmd()().(ErrMsg); !ok { + t.Error("loadCmd on a closed db should report an error") } } -func TestIsBusy_EntriesMode(t *testing.T) { - m := ReportsModel{mode: reportsModeEntries} - if !m.IsBusy() { - t.Error("IsBusy() in entries mode should be true — it should capture all keystrokes like filter mode does") +// TestEntryCols_RowWidthMatchesDivider: an entry row wider than the +// content column wraps onto a second line under app.go's Width(cw) and +// pushes the header off screen. +func TestEntryCols_RowWidthMatchesDivider(t *testing.T) { + for _, w := range []int{64, 80, 100, 120, 150, 200} { + m := ReportsModel{width: w} + date, task, dur, earned, status := m.entryCols() + if got := theme.Gutter + date + task + dur + earned + status; got != usableWidth(w) { + t.Errorf("width %d: entry row is %d wide, want %d", w, got, usableWidth(w)) + } } } diff --git a/internal/ui/views/reports_view.go b/internal/ui/views/reports_view.go new file mode 100644 index 0000000..2a6f104 --- /dev/null +++ b/internal/ui/views/reports_view.go @@ -0,0 +1,694 @@ +package views + +// Drawing the Reports tab (ALI-2618). From theme.WideMin columns, and tall +// enough, the hours bars sit left of the table, as on the 140×40 board; +// narrower or shorter terminals stack them, with shorter bars, and drop +// the bars when the table would get fewer than minReportRows rows. +// +// Colour is never the only signal: the on range chip is a filled block, +// each bar has its hours written under it and today's day name is bold, +// invoiced and paid are counts, and the selected row has the ▌ cursor. + +import ( + "fmt" + "strings" + "time" + + "github.com/aliasproject/notch/internal/model" + "github.com/aliasproject/notch/internal/report" + "github.com/aliasproject/notch/internal/status" + "github.com/aliasproject/notch/internal/theme" + "github.com/charmbracelet/lipgloss" +) + +// Fixed rows of the screen's top: the range chips and a blank, then the +// stat cards and a blank. Wide cards are boxes (two borders and three +// lines); compact ones drop the top and bottom borders. +const ( + reportCardRows = 5 + reportCardRowsCompact = 3 + reportTopRows = 2 + reportCardRows + 1 + reportTopRowsCompact = 2 + reportCardRowsCompact + 1 + // reportTableFixed is the table's title, column titles and rule above + // the rows, and the rule and total below them. + reportTableFixed = 5 + // minReportRows is the fewest table rows the layout keeps; the bars go + // before the table gets fewer. + minReportRows = 3 +) + +// barsRows is the chart's height at a bar height: its title, the bars, and +// the day and hours labels under them. +func barsRows(barRows int) int { return 1 + barRows + 2 } + +func (m ReportsModel) innerWidth() int { return usableWidth(m.width) } +func (m ReportsModel) innerHeight() int { return max(1, m.height-2) } + +// wide reports whether the bars sit beside the table: theme.WideMin +// columns and up, with room under the cards for the bars and the running +// note. +func (m ReportsModel) wide() bool { + return m.width >= theme.WideMin && + m.innerHeight()-reportTopRows >= max(barsRows(theme.BarRows)+2, reportTableFixed+minReportRows) +} + +// compactChartRows is what the stacked bars take, with the blank under +// them, or 0 when the table needs the room. +func (m ReportsModel) compactChartRows() int { + rows := barsRows(theme.BarRowsCompact) + 1 + if m.compactRowsWith(rows) < minReportRows { + return 0 + } + return rows +} + +func (m ReportsModel) compactRowsWith(chart int) int { + rows := m.innerHeight() - reportTopRowsCompact - chart - reportTableFixed + if m.running() != nil { + rows-- // the running note under the table + } + return rows +} + +// rowsBudget is how many table rows fit. +func (m ReportsModel) rowsBudget() int { + if m.wide() { + return max(1, m.innerHeight()-reportTopRows-reportTableFixed) + } + return max(1, m.compactRowsWith(m.compactChartRows())) +} + +// clampOffset keeps the cursor's row inside the visible window, scrolling +// only when it reaches an edge. +func (m *ReportsModel) clampOffset() { + budget := m.rowsBudget() + n := len(m.lines) + if n <= budget { + m.offset = 0 + return + } + if m.cursor < m.offset { + m.offset = m.cursor + } + if m.cursor >= m.offset+budget { + m.offset = m.cursor - budget + 1 + } + m.offset = max(0, min(m.offset, n-budget)) +} + +// ── View ────────────────────────────────────────────────────────────────────── + +func (m ReportsModel) View() string { + w, h := m.innerWidth(), m.innerHeight() + switch m.mode { + case reportsModeCustom: + return modalOver(m.renderReport(), w, h, m.viewCustom(w, h)) + case reportsModeEntries: + return m.renderEntriesView() + case reportsModeEditEntry: + return modalOver(m.renderEntriesView(), w, h, m.editForm.view(w, h, "Save")) + } + return m.renderReport() +} + +// renderReport is the report screen: chips, cards, then the bars and the +// table, side by side or stacked. +func (m ReportsModel) renderReport() string { + w := m.innerWidth() + now := m.clock() + out := []string{m.renderRangeChips(w), blankLine(w)} + wide := m.wide() + out = append(out, m.renderCards(w, wide)...) + out = append(out, blankLine(w)) + + if wide { + tableW := w / 2 + chartW := w - tableW - theme.PaneGap + left := m.renderBars(chartW, theme.BarRows, now) + if m.running() != nil { + left = append(left, blankLine(chartW), renderSegs(cBg, seg{s: truncate(runningNote, chartW), fg: cSubtle})) + } + right := m.renderTable(tableW) + for i := 0; i < max(len(left), len(right)); i++ { + l, r := blankLine(chartW), blankLine(tableW) + if i < len(left) { + l = padTo(left[i], chartW) + } + if i < len(right) { + r = right[i] + } + out = append(out, l+blankLine(theme.PaneGap)+r) + } + return strings.Join(out, "\n") + } + + if m.compactChartRows() > 0 { + out = append(out, m.renderBars(w, theme.BarRowsCompact, now)...) + out = append(out, blankLine(w)) + } + out = append(out, m.renderTable(w)...) + if m.running() != nil { + out = append(out, padTo(renderSegs(cBg, seg{s: truncate(runningNote, w), fg: cSubtle}), w)) + } + return strings.Join(out, "\n") +} + +// runningNote says why the running timer's time isn't in the report. +const runningNote = "Running timer not counted until it stops." + +// ── Range chips ─────────────────────────────────────────────────────────────── + +type reportsChip struct { + key, label string + preset reportsPreset +} + +var reportsChips = []reportsChip{ + {"t", "Today", reportsPresetToday}, + {"w", "Week", reportsPresetWeek}, + {"m", "Month", reportsPresetMonth}, + {"y", "Year", reportsPresetYear}, + {"a", "All", reportsPresetAll}, + {"f", "Custom…", reportsPresetCustom}, +} + +// renderRangeChips is the Range line: each chip with its key before it in +// subtle, as on the Timers tab, the on one filled; then the dates, when +// there's room. +func (m ReportsModel) renderRangeChips(w int) string { + left := []seg{{s: "Range", fg: cSubtle}, {s: " "}} + for _, c := range reportsChips { + chip := seg{s: " " + c.label + " ", fg: cDim} + if c.preset == m.preset { + chip = seg{s: chip.s, fg: cBg, bg: cPrimary, bold: true} + } + left = append(left, seg{s: " "}, seg{s: c.key, fg: cSubtle}, chip) + } + if room := w - segsWidth(left) - 3; room >= 8 { + left = append(left, seg{s: " "}, seg{s: truncate(rangeLabel(m.rng), room), fg: cDim}) + } + return spread(w, cBg, left, nil) +} + +// rangeLabel names a range's dates: "Nov 30 – Dec 3, 2026", "Dec 3, 2026" +// for one day, "From …" or "Up to …" for an open side, or "All time". +func rangeLabel(r report.Range) string { + parse := func(s string) (time.Time, bool) { + t, err := time.ParseInLocation("2006-01-02", s, time.Local) + return t, err == nil + } + from, okF := parse(r.From) + to, okT := parse(r.To) + switch { + case !okF && !okT: + return "All time" + case !okF: + return "Up to " + to.Format("Jan 2, 2006") + case !okT: + return "From " + from.Format("Jan 2, 2006") + case r.From == r.To: + return to.Format("Jan 2, 2006") + case from.Year() == to.Year(): + return from.Format("Jan 2") + " – " + to.Format("Jan 2, 2006") + } + return from.Format("Jan 2, 2006") + " – " + to.Format("Jan 2, 2006") +} + +// ── Stat cards ──────────────────────────────────────────────────────────────── + +type statCard struct { + label, value, sub, short string // short: sub for a narrow card + fg lipgloss.Color +} + +// statCards are the four cards, from report.Report: the hours, what they +// earned, what's invoiced and not paid, and what isn't invoiced yet. +func (m ReportsModel) statCards() []statCard { + rep := m.rep + avg := "avg —" + if rep.Seconds > 0 { + avg = "avg " + formatMoney(rep.AverageRate) + "/h" + } + return []statCard{ + {label: "HOURS", value: model.FormatDuration(time.Duration(rep.Seconds) * time.Second), + sub: fmt.Sprintf("%d %s", rep.Entries, plural(rep.Entries, "entry", "entries")), fg: cHighlight}, + {label: "EARNED", value: formatMoney(rep.Earned), sub: avg, fg: cGreen}, + {label: "OUTSTANDING", value: formatMoney(rep.Outstanding), sub: "invoiced, not paid", short: "not paid yet", fg: cAmber}, + {label: "UNBILLED", value: formatMoney(rep.Unbilled), + sub: fmt.Sprintf("%d %s", rep.UnbilledEntries, plural(rep.UnbilledEntries, "entry", "entries")), fg: cText}, + } +} + +// renderCards draws the four cards across w, tui-card-gap apart: boxed when +// wide, and as three lines after a rule when compact. +func (m ReportsModel) renderCards(w int, boxed bool) []string { + cards := m.statCards() + cw := max(6, (w-(len(cards)-1)*theme.CardGap)/len(cards)) + if !boxed { + return renderCardsCompact(cards, cw, w) + } + inner := cw - 4 // the borders and a space inside each + out := make([]string, reportCardRows) + gap := seg{s: strings.Repeat(" ", theme.CardGap)} + for i, c := range cards { + sub := c.sub + if c.short != "" && len([]rune(sub)) > inner { + sub = c.short + } + rows := [3]seg{ + {s: fit(c.label, inner), fg: cSubtle, bold: true}, + {s: fit(c.value, inner), fg: c.fg, bold: true}, + {s: fit(sub, inner), fg: cSubtle}, + } + edge := seg{s: "╭" + strings.Repeat("─", cw-2) + "╮", fg: cBorder} + foot := seg{s: "╰" + strings.Repeat("─", cw-2) + "╯", fg: cBorder} + if i > 0 { + out[0] += renderSegs(cBg, gap) + out[4] += renderSegs(cBg, gap) + } + out[0] += renderSegs(cBg, edge) + out[4] += renderSegs(cBg, foot) + for r, s := range rows { + if i > 0 { + out[r+1] += renderSegs(cBg, gap) + } + out[r+1] += renderSegs(cBg, boxSide(), seg{s: " "}, s, seg{s: " "}, boxSide()) + } + } + for i := range out { + out[i] = padTo(out[i], w) + } + return out +} + +// renderCardsCompact draws the cards as three lines each, after a rule in +// border, cw wide. +func renderCardsCompact(cards []statCard, cw, w int) []string { + inner := cw - 2 // the rule and a space + out := make([]string, reportCardRowsCompact) + gap := seg{s: strings.Repeat(" ", theme.CardGap)} + for i, c := range cards { + sub := c.sub + if c.short != "" && len([]rune(sub)) > inner { + sub = c.short + } + rows := [3]seg{ + {s: fit(c.label, inner), fg: cSubtle, bold: true}, + {s: fit(c.value, inner), fg: c.fg, bold: true}, + {s: fit(sub, inner), fg: cSubtle}, + } + for r, s := range rows { + if i > 0 { + out[r] += renderSegs(cBg, gap) + } + out[r] += renderSegs(cBg, boxSide(), seg{s: " "}, s) + } + } + for i := range out { + out[i] = padTo(out[i], w) + } + return out +} + +// ── Hours bars ──────────────────────────────────────────────────────────────── + +// bar is one bar: a day, or a week, month or year of them when the range +// has more days than fit. +type bar struct { + label string + secs int64 + today bool +} + +// barGlyphs are the eighth blocks a bar's top row is drawn in. +var barGlyphs = []rune(" ▁▂▃▄▅▆▇█") + +// hoursLabel is a bar's value: "—" for none, "2.5h" under ten hours, then +// whole hours. +func hoursLabel(secs int64) string { + h := float64(secs) / 3600 + switch { + case secs == 0: + return "—" + case h < 9.95: + return fmt.Sprintf("%.1fh", h) + } + return fmt.Sprintf("%.0fh", h) +} + +// chartBars groups the report's days into bars that fit w: one a day when +// they fit, else one a week, a month or a year. A range of years too long +// for even that keeps its latest. slot is each bar's width with its gap, +// and barW the bar's own. +func chartBars(days []report.Day, w int, today string) (bars []bar, slot, barW int) { + if len(days) == 0 { + return nil, 0, 0 + } + dates := make([]time.Time, len(days)) + for i, d := range days { + dates[i], _ = time.ParseInLocation("2006-01-02", d.Date, time.Local) + } + oneYear := dates[0].Year() == dates[len(dates)-1].Year() + type level struct { + key func(time.Time) string + label func(time.Time) string + } + dayLabel := func(t time.Time) string { return t.Format("Jan 2") } + if len(days) <= 7 { + dayLabel = func(t time.Time) string { return t.Format("Mon") } + } + monthLabel := func(t time.Time) string { return t.Format("Jan '06") } + if oneYear { + monthLabel = func(t time.Time) string { return t.Format("Jan") } + } + levels := []level{ + {func(t time.Time) string { return t.Format("2006-01-02") }, dayLabel}, + {func(t time.Time) string { return status.StartOfWeek(t).Format("2006-01-02") }, func(t time.Time) string { return t.Format("Jan 2") }}, + {func(t time.Time) string { return t.Format("2006-01") }, monthLabel}, + {func(t time.Time) string { return t.Format("2006") }, func(t time.Time) string { return t.Format("2006") }}, + } + minSlot := 0 + for _, lv := range levels { + bars = bars[:0] + last := "" + for i, d := range days { + k := lv.key(dates[i]) + if k != last || len(bars) == 0 { + bars = append(bars, bar{label: lv.label(dates[i])}) + last = k + } + b := &bars[len(bars)-1] + b.secs += d.Seconds + b.today = b.today || d.Date == today + } + minSlot = 0 + for _, b := range bars { + minSlot = max(minSlot, lipgloss.Width(b.label), lipgloss.Width(hoursLabel(b.secs))) + } + minSlot++ // a gap after each + if len(bars)*minSlot <= w { + break + } + } + if n := max(1, w/minSlot); len(bars) > n { + bars = bars[len(bars)-n:] + } + slot = max(minSlot, min(theme.BarWidth+theme.BarGap, w/len(bars))) + barW = max(1, min(theme.BarWidth, slot-1)) + return bars, slot, barW +} + +// chartDays is the report's days for the bars. This week runs to today, +// as in "notch report"; its bars run on to Sunday, empty, as on the board, +// so the week always reads Mon to Sun. +func (m ReportsModel) chartDays() []report.Day { + days := m.rep.Days + if m.preset != reportsPresetWeek || len(days) == 0 { + return days + } + last, err := time.ParseInLocation("2006-01-02", days[len(days)-1].Date, time.Local) + if err != nil { + return days + } + days = append([]report.Day(nil), days...) + for d := last.AddDate(0, 0, 1); d.Weekday() != time.Monday; d = d.AddDate(0, 0, 1) { + days = append(days, report.Day{Date: d.Format("2006-01-02")}) + } + return days +} + +// renderBars is the BY DAY chart, w wide: its title, the bars barRows +// tall in eighth blocks, then each bar's day and hours. Today's bar is in +// success and its day name in bold. +func (m ReportsModel) renderBars(w, barRows int, now time.Time) []string { + title := renderSegs(cBg, seg{s: fit("BY DAY", w), fg: cSubtle, bold: true}) + indent := theme.Gutter + bars, slot, barW := chartBars(m.chartDays(), w-indent, now.Format("2006-01-02")) + if len(bars) == 0 { + out := []string{title} + for i := 0; i < barRows+2; i++ { + out = append(out, blankLine(w)) + } + out[barRows] = padTo(renderSegs(cBg, seg{s: strings.Repeat(" ", indent)}, seg{s: truncate("No time in this range.", w-indent), fg: cSubtle}), w) + return out + } + var top int64 + for _, b := range bars { + top = max(top, b.secs) + } + eighths := make([]int, len(bars)) + for i, b := range bars { + if b.secs > 0 { + eighths[i] = max(1, int(b.secs*int64(barRows*8)/top)) + } + } + lead := seg{s: strings.Repeat(" ", indent)} + out := []string{title} + for r := 0; r < barRows; r++ { + segs := []seg{lead} + base := (barRows - 1 - r) * 8 + for i, b := range bars { + fill := min(8, max(0, eighths[i]-base)) + fg := cPrimary + if b.today { + fg = cGreen + } + segs = append(segs, seg{s: strings.Repeat(string(barGlyphs[fill]), barW), fg: fg}, seg{s: strings.Repeat(" ", slot-barW)}) + } + out = append(out, padTo(renderSegs(cBg, segs...), w)) + } + days, hours := []seg{lead}, []seg{lead} + for _, b := range bars { + d := seg{s: fit(b.label, slot), fg: cSubtle} + if b.today { + d = seg{s: d.s, fg: cText, bold: true} + } + days = append(days, d) + hours = append(hours, seg{s: fit(hoursLabel(b.secs), slot), fg: cDim}) + } + return append(out, padTo(renderSegs(cBg, days...), w), padTo(renderSegs(cBg, hours...), w)) +} + +// ── Table ───────────────────────────────────────────────────────────────────── + +// reportNameW is the NAME column's width in a table w wide: what the cursor +// gutter and the fixed columns leave. +func reportNameW(w int) int { + return max(4, w-theme.Gutter-theme.ReportColHours-2*theme.ReportColCount-theme.ReportColEarned-theme.ReportTrail) +} + +// reportRowSegs lays out one row of the table after its lead: the name, +// then hours, invoiced, paid and earned, right-aligned. +func reportRowSegs(w int, name string, nameSeg seg, hours, inv, paid, earned seg) []seg { + nameW := reportNameW(w) + nameSeg.s = fit(truncate(name, nameW-1), nameW) + hours.s = fitRight(hours.s, theme.ReportColHours) + inv.s = fitRight(inv.s, theme.ReportColCount) + paid.s = fitRight(paid.s, theme.ReportColCount) + earned.s = fitRight(earned.s, theme.ReportColEarned) + return []seg{nameSeg, hours, inv, paid, earned, {s: strings.Repeat(" ", theme.ReportTrail)}} +} + +func earnedCell(x float64) string { + if x == 0 { + return "—" + } + return formatMoney(x) +} + +// renderTable is the BY CLIENT AND PROJECT table, w wide: its title, the +// column titles, the window of client and project rows, and the total. +func (m ReportsModel) renderTable(w int) []string { + head := func(s string) seg { return seg{s: s, fg: cSubtle, bold: true} } + lead := seg{s: strings.Repeat(" ", theme.Gutter)} + out := []string{ + renderSegs(cBg, seg{s: fit("BY CLIENT AND PROJECT", w), fg: cSubtle, bold: true}), + spread(w, cBg, append([]seg{lead}, reportRowSegs(w, "NAME", head(""), head("HOURS"), head("INVOICED"), head("PAID"), head("EARNED"))...), nil), + } + budget := m.rowsBudget() + start := m.offset + end := min(len(m.lines), start+budget) + out = append(out, rule(w, start > 0, end < len(m.lines))) + if len(m.lines) == 0 { + out = append(out, renderSegs(cBg, lead, seg{s: fit(truncate("No finished time in this range.", w-theme.Gutter), w-theme.Gutter), fg: cSubtle})) + } + for i := start; i < end; i++ { + out = append(out, m.renderLine(m.lines[i], i == m.cursor, w)) + } + if len(m.lines) > budget { + for n := end - start; n < budget; n++ { + out = append(out, blankLine(w)) + } + } + rep := m.rep + total := reportRowSegs(w, "Total", seg{bold: true}, + seg{s: model.FormatDuration(time.Duration(rep.Seconds) * time.Second), bold: true}, + seg{s: fmt.Sprintf("%d/%d", rep.Invoiced, rep.Entries), fg: cAccent, bold: true}, + seg{s: fmt.Sprintf("%d/%d", rep.Paid, rep.Entries), fg: cGreen, bold: true}, + seg{s: earnedCell(rep.Earned), bold: true}) + return append(out, rule(w, false, false), spread(w, cBg, append([]seg{lead}, total...), nil)) +} + +// renderLine draws a client row (bold) or a project row (indented, dim). +// The selected one sits on bg_alt with the ▌ cursor before it. +func (m ReportsModel) renderLine(l reportLine, sel bool, w int) string { + bg := cBg + lead := seg{s: strings.Repeat(" ", theme.Gutter)} + if sel { + bg = cBgAlt + lead = seg{s: theme.GlyphCursor + strings.Repeat(" ", theme.Gutter-lipgloss.Width(theme.GlyphCursor)), fg: cPrimary} + } + name := l.name + nameSeg, numFg, bold := seg{bold: true}, cText, true + if !l.client { + name = strings.Repeat(" ", theme.ReportIndent) + name + nameSeg, numFg, bold = seg{fg: cDim, bold: sel}, cDim, false + } + segs := reportRowSegs(w, name, nameSeg, + seg{s: model.FormatDuration(time.Duration(l.Seconds) * time.Second), fg: numFg, bold: bold}, + seg{s: fmt.Sprintf("%d/%d", l.Invoiced, l.Entries), fg: cAccent}, + seg{s: fmt.Sprintf("%d/%d", l.Paid, l.Entries), fg: cGreen}, + seg{s: earnedCell(l.Earned), fg: numFg, bold: bold}) + return spread(w, bg, append([]seg{lead}, segs...), nil) +} + +// ── Custom range modal ──────────────────────────────────────────────────────── + +func (m ReportsModel) viewCustom(w, h int) []string { + sw := stripWidth(modalInner(theme.ModalWidth, w)) + field := func(label string, idx int, in, hint string) modalField { + return modalField{ + label: label, + focused: m.focusIdx == idx, + mark: m.focusIdx == idx, + strip: true, + value: in, + err: m.errs[idx], + hint: hint, + } + } + return formModal{ + title: "Custom range", + fields: []modalField{ + field("From", customFieldFrom, stripInput(m.fromInput, sw), "First day, YYYY-MM-DD; blank for no start"), + field("To", customFieldTo, stripInput(m.toInput, sw), "Last day; blank for no end"), + }, + left: []modalButton{ + {label: "Apply", kind: buttonPrimary, focused: m.focusIdx == customFieldApply}, + {label: "Cancel", kind: buttonSecondary, focused: m.focusIdx == customFieldCancel}, + }, + hint: "tab next · esc close", + }.render(w, h) +} + +// ── Entries behind a row ────────────────────────────────────────────────────── + +// entryCols returns the entries table's column widths, for both its drawing +// and its scrolling. TASK takes what's left. +func (m ReportsModel) entryCols() (date, task, dur, earned, stat int) { + date, dur, earned, stat = 14, 12, 12, 12 + task = usableWidth(m.width) - (theme.Gutter + date + dur + earned + stat) + if task < 20 { + // Narrow terminal: tighten the fixed columns to their widest + // content ("Sep 10, 2026", "12:34:56", "$1234.56", "◐ invoiced") + // before squeezing TASK, so no row wraps. + date, dur, earned, stat = 13, 10, 10, 11 + task = max(8, usableWidth(m.width)-(theme.Gutter+date+dur+earned+stat)) + } + return date, task, dur, earned, stat +} + +// renderEntryDetail shows the selected entry's start and end, notes and +// status, like the Timers tab's detail. +func (m ReportsModel) renderEntryDetail(e *model.Entry) string { + started := e.StartTime.Local().Format("Jan 2, 2006 3:04 PM") + dateLine := StyleMuted.Render("Started ") + StyleTableRow.Render(started) + if e.EndTime != nil { + dateLine += StyleMuted.Render(" – ") + StyleTableRow.Render(e.EndTime.Local().Format("3:04 PM")) + } + notesLine := StyleMuted.Render(noteDetailLabel) + formatNoteDetail(e.Notes, usableWidth(m.width)) + statusLine := StyleMuted.Render("Status ") + invoiceLabel(e) + return strings.Join([]string{dateLine, notesLine, statusLine}, "\n") +} + +// entriesRowsBudget is how many entry rows fit: the header, a blank, the +// column titles, the rule and a blank before the detail, then the detail. +func (m ReportsModel) entriesRowsBudget() int { + detailLines := 1 + if m.selectedEntry() != nil { + detailLines = entryDetailLines + } + return max(1, m.height-2-5-detailLines) +} + +// clampEntriesOffset keeps entriesCursor's row in the visible window. +func (m *ReportsModel) clampEntriesOffset() { + n := len(m.selectedEntries()) + budget := m.entriesRowsBudget() + if n <= budget { + m.entriesOffset = 0 + return + } + if m.entriesCursor < m.entriesOffset { + m.entriesOffset = m.entriesCursor + } + if m.entriesCursor >= m.entriesOffset+budget { + m.entriesOffset = m.entriesCursor - budget + 1 + } + m.entriesOffset = max(0, min(m.entriesOffset, n-budget)) +} + +// renderEntriesView is the entries behind the selected row, newest first, +// with the selected entry's details under them. +func (m ReportsModel) renderEntriesView() string { + l := m.selectedLine() + if l == nil { + return m.renderReport() + } + title := l.name + if !l.client { + title = l.clientName + " › " + l.name + } + header := StyleTitle.Render(title) + + StyleMuted.Render(" · ") + + StyleMuted.Render(model.FormatDuration(time.Duration(l.Seconds)*time.Second)+" · "+earnedCell(l.Earned)+" · "+rangeLabel(m.rng)) + entries := m.selectedEntries() + if len(entries) == 0 { + return header + "\n\n" + StyleMuted.Render("No entries for this period.") + } + + colDate, colTask, colDur, colEarned, colStatus := m.entryCols() + totalW := usableWidth(m.width) + hdr := RowPrefix(false) + + StyleTableHeader.Width(colDate).Render("Date") + + StyleTableHeader.Width(colTask).Render("Task") + + StyleTableHeader.Width(colDur).Align(lipgloss.Right).Render("Duration") + + StyleTableHeader.Width(colEarned).Align(lipgloss.Right).Render("Earned") + + StyleTableHeader.Width(colStatus).Render("Status") + + m.clampEntriesOffset() + start := m.entriesOffset + end := min(len(entries), start+m.entriesRowsBudget()) + rows := []string{hdr, rule(totalW, start > 0, end < len(entries))} + now := m.clock() + for i := start; i < end; i++ { + e := entries[i] + sel := i == m.entriesCursor + base, rowBg := StyleTableRow, cBg + if sel { + base, rowBg = StyleTableRowSel, cBgAlt + } + statText, statFg := entryStatus(e) + rows = append(rows, RowPrefix(sel)+ + base.Width(colDate).Render(e.StartTime.Local().Format("Jan 2, 2006"))+ + base.Width(colTask).Render(truncate(e.Task, colTask-3))+ + base.Width(colDur).Align(lipgloss.Right).Render(model.FormatDuration(e.Duration()))+ + base.Width(colEarned).Align(lipgloss.Right).Render(earnedText(e, now))+ + lipgloss.NewStyle().Foreground(statFg).Background(rowBg).Padding(0, 1).Width(colStatus).Render(statText)) + } + detail := "" + if e := m.selectedEntry(); e != nil { + detail = m.renderEntryDetail(e) + } + return header + "\n\n" + strings.Join(rows, "\n") + "\n\n" + detail +} From 5ec09c10578bebafb1058bab8f18afa9daba9838 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 10:39:06 -0700 Subject: [PATCH 2/4] Reports review fixes (ALI-2618) - Presets follow the clock: each reload works out today, this week, this month or this year again, so a tab left open past midnight or into a new month shows (and exports) the current range. Custom ranges stay put. - The table cursor and the entries list follow their row by client and project ID, and the entries cursor its entry by ID, across reloads. When the list's row leaves the report, the list closes and the status line says so; an open edit form closes to the report. - A database change from another process (dbWatch, and the fallback tick) reloads the Reports tab as well as Timers. - CSV exports are created 0600, and a download folder that can't be written to falls through to the next (~/Downloads, then home). user-dirs.dirs values in single quotes, unquoted, after export, or followed by a comment now parse. - An entry gone before its edit form opens says so on the status line; the old message was never shown. - Amounts are never cut: cards, the table and the entries list drop the cents, then go compact ($123k, $1.2M), with the same fitMoney and fitRate as the Clients tab in ALI-2617 (in money.go, to merge into one copy). Hours too wide show as whole hours. - Layout counts come from what's drawn (card lines, the table's fixed lines, entry columns from their widest values and the cell padding), and two new tokens: tui-card-pad and tui-report-min-rows. --- README.md | 2 +- design/build/main.go | 2 + design/tokens.json | 2 + internal/theme/tokens_gen.go | 8 + internal/ui/app.go | 5 +- internal/ui/render_test.go | 46 +++++ internal/ui/views/money.go | 58 ++++++ internal/ui/views/reports.go | 157 ++++++++++++---- internal/ui/views/reports_export.go | 89 ++++++++-- internal/ui/views/reports_test.go | 229 +++++++++++++++++++++++- internal/ui/views/reports_view.go | 266 +++++++++++++++++----------- 11 files changed, 692 insertions(+), 172 deletions(-) create mode 100644 internal/ui/views/money.go diff --git a/README.md b/README.md index d75af87..2bf78db 100644 --- a/README.md +++ b/README.md @@ -306,7 +306,7 @@ The Reports tab covers the finished entries that started in the chosen range (th - **By day** — hours as bars, each with its hours written under it; a range with more days than fit shows a bar per week, month or year instead - **By client and project** — each client, with its projects under it: hours, how many entries are invoiced and paid, and earned (hours × the client's current rate) -`e` exports the range's entries as CSV, the same rows as `notch report --csv`, to your downloads folder (`XDG_DOWNLOAD_DIR`, else `~/Downloads`, else your home folder). The file is named for the range, such as `notch-2026-11-30-to-2026-12-03.csv`; if that name is taken, the export gets ` (2)`, ` (3)` and so on, so it never overwrites a file. The status line shows where it went. +`e` exports the range's entries as CSV, the same rows as `notch report --csv`, to your downloads folder (`XDG_DOWNLOAD_DIR`, else `~/Downloads`, else your home folder, skipping one it can't write to). Only you can read the file, since it holds earnings and notes. It is named for the range, such as `notch-2026-11-30-to-2026-12-03.csv`; if that name is taken, the export gets ` (2)`, ` (3)` and so on, so it never overwrites a file. The status line shows where it went. --- diff --git a/design/build/main.go b/design/build/main.go index 62c0032..ac15b71 100644 --- a/design/build/main.go +++ b/design/build/main.go @@ -357,6 +357,8 @@ func renderPalette(t *Tokens) ([]byte, error) { {"tui-report-col-earned", "ReportColEarned"}, {"tui-report-trail", "ReportTrail"}, {"tui-report-indent", "ReportIndent"}, + {"tui-card-pad", "CardPad"}, + {"tui-report-min-rows", "ReportMinRows"}, } { v, err := integer(t.Spacing, c.token) if err != nil { diff --git a/design/tokens.json b/design/tokens.json index fd80ad8..9de4604 100644 --- a/design/tokens.json +++ b/design/tokens.json @@ -98,6 +98,8 @@ { "name": "tui-report-col-count", "value": 10, "usage": "TUI: the Reports table's INVOICED and PAID columns, each right-aligned." }, { "name": "tui-report-col-earned", "value": 13, "usage": "TUI: the Reports table's EARNED column, right-aligned, room for $100,000.00 and a gap." }, { "name": "tui-report-trail", "value": 2, "usage": "TUI: blank columns after the Reports table's EARNED column." }, + { "name": "tui-card-pad", "value": 1, "usage": "TUI: blank columns inside a Reports stat card's border, on each side of its text." }, + { "name": "tui-report-min-rows", "value": 3, "usage": "TUI: the fewest client and project rows the Reports table keeps; the hours bars go before it gets fewer." }, { "name": "tui-report-indent", "value": 2, "usage": "TUI: how far a project's name sits in from its client's in the Reports table." }, { "name": "tui-min-width", "value": 64, "usage": "TUI: the narrowest terminal notch draws, in cells, measured from the views: the widest fixed line is the Projects tab's at 57 cells, 61 with the two margins; the compact Timers range chips need 48, and the Reports range chips 58. Narrower terminals get a centred \"Terminal too small\" message." }, { "name": "tui-min-height", "value": 22, "usage": "TUI: the shortest terminal notch draws, in rows: the chrome (4), the body's top and bottom padding (2), the compact Timers screen's fixed rows (14) and two list rows (a day header and the selected entry). A wide terminal this short gets the compact layout, since the wide one needs 23 rows (see tui-wide). Shorter terminals get a centred \"Terminal too small\" message." }, diff --git a/internal/theme/tokens_gen.go b/internal/theme/tokens_gen.go index 82e5954..5039c21 100644 --- a/internal/theme/tokens_gen.go +++ b/internal/theme/tokens_gen.go @@ -235,3 +235,11 @@ const ReportTrail = 2 // ReportIndent (tui-report-indent). TUI: how far a project's name sits in // from its client's in the Reports table. const ReportIndent = 2 + +// CardPad (tui-card-pad). TUI: blank columns inside a Reports stat card's +// border, on each side of its text. +const CardPad = 1 + +// ReportMinRows (tui-report-min-rows). TUI: the fewest client and project +// rows the Reports table keeps; the hours bars go before it gets fewer. +const ReportMinRows = 3 diff --git a/internal/ui/app.go b/internal/ui/app.go index fd55e9c..017b342 100644 --- a/internal/ui/app.go +++ b/internal/ui/app.go @@ -226,7 +226,7 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { m.tickCount++ if m.tickCount >= tickFallbackTicks { m.tickCount = 0 - cmds = append(cmds, m.timers.Init()) + cmds = append(cmds, m.timers.Init(), m.reports.Init()) } if theme.CheckReload() { refreshAppTheme() @@ -250,6 +250,9 @@ func (m AppModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { // own unconditional theme-reload check): the other three tabs // simply have no case for timerEntriesMsg and ignore it. cmds = append(cmds, m.timers.Init()) + // The Reports tab's report too, so a stopped timer or a CLI edit + // shows there, and e exports what's in the database now. + cmds = append(cmds, m.reports.Init()) case themeWatchMsg: cmds = append(cmds, watchThemeCmd()) diff --git a/internal/ui/render_test.go b/internal/ui/render_test.go index b491291..48a3378 100644 --- a/internal/ui/render_test.go +++ b/internal/ui/render_test.go @@ -173,3 +173,49 @@ func TestRenderReportsSample(t *testing.T) { } } } + +// runCmd runs cmd and every command a batch holds, and feeds their +// messages to m. +func runCmd(m AppModel, cmd tea.Cmd) AppModel { + if cmd == nil { + return m + } + switch msg := cmd().(type) { + case nil: + case tea.BatchMsg: + for _, c := range msg { + m = runCmd(m, c) + } + default: + u, _ := m.Update(msg) + m = u.(AppModel) + } + return m +} + +// A write from another process (dbWatch) reloads the Reports tab too, so +// it and its export show the database as it is now. +func TestDBWatch_ReloadsReports(t *testing.T) { + m := sampleApp(t, 140, 40) + m.dbWatch = nil // no watcher to wait on in the test + u, cmd := m.Update(runeKey('4')) + m = runCmd(u.(AppModel), cmd) + u, cmd = m.Update(runeKey('a')) // all time, whatever today's date + m = runCmd(u.(AppModel), cmd) + before := strings.Count(plainText(m.View()), "Late addition") + c, err := m.db.CreateClient("Late addition", 10) + if err != nil { + t.Fatal(err) + } + p, _ := m.db.CreateProject(c.ID, "Late addition project") + start := time.Now().Add(-2 * time.Hour) + end := start.Add(time.Hour) + if _, err := m.db.AddEntry(p.ID, "from the CLI", "", start, &end); err != nil { + t.Fatal(err) + } + u, cmd = m.Update(dbWatchMsg{}) + m = runCmd(u.(AppModel), cmd) + if after := strings.Count(plainText(m.View()), "Late addition"); before != 0 || after == 0 { + t.Errorf("Reports should show the new client after dbWatch (before %d, after %d):\n%s", before, after, plainText(m.View())) + } +} diff --git a/internal/ui/views/money.go b/internal/ui/views/money.go new file mode 100644 index 0000000..7af550c --- /dev/null +++ b/internal/ui/views/money.go @@ -0,0 +1,58 @@ +package views + +// Fitting amounts to a column without cutting them. These are the same +// functions, rules and output as the Clients tab's in ALI-2617 (#16), so +// both tabs show amounts the same way. When both PRs are on main, keep one +// copy: delete this file in favour of clients.go's, or the other way round. + +import ( + "fmt" + "math" + "strings" + + "github.com/charmbracelet/lipgloss" +) + +// fitMoney is x as money in at most w cells, never cut: "$123,456.78", +// then without the cents, "$123,457", then compact, "$123k" or "$1.2M". +func fitMoney(x float64, w int) string { + for _, s := range []string{formatMoney(x), wholeMoney(x)} { + if lipgloss.Width(s) <= w { + return s + } + } + return compactMoney(x) +} + +// fitRate is an hourly rate in at most w cells, shortened like fitMoney. +func fitRate(r float64, w int) string { + for _, s := range []string{formatRate(r), wholeMoney(r) + "/h"} { + if lipgloss.Width(s) <= w { + return s + } + } + return compactMoney(r) + "/h" +} + +// wholeMoney is x rounded to whole dollars: "$123,457". +func wholeMoney(x float64) string { + return strings.TrimSuffix(formatMoney(math.Round(x)), ".00") +} + +// compactMoney is x in thousands or millions: "$950", "$124k", "$1.2M". +func compactMoney(x float64) string { + sign := "" + if x < 0 { + sign, x = "-", -x + } + switch { + case math.Round(x) < 1000: + return sign + fmt.Sprintf("$%.0f", x) + case math.Round(x/1000) < 1000: + return sign + fmt.Sprintf("$%.0fk", x/1000) + case x < 9.95e6: + return sign + strings.Replace(fmt.Sprintf("$%.1fM", x/1e6), ".0M", "M", 1) + default: + return sign + fmt.Sprintf("$%.0fM", x/1e6) + } +} diff --git a/internal/ui/views/reports.go b/internal/ui/views/reports.go index 8cf0418..74ab8d9 100644 --- a/internal/ui/views/reports.go +++ b/internal/ui/views/reports.go @@ -57,12 +57,18 @@ const ( customFieldCount = customFieldApply ) +// rowKey names a table row across reloads: a client, or one of its +// projects. +type rowKey struct { + client bool + clientID int64 + projectID int64 // 0 on a client's row +} + // reportLine is one row of the table: a client, or one of its projects // under it. type reportLine struct { - client bool - clientID int64 - projectID int64 // 0 on a client's row + rowKey name string clientName string report.Counts @@ -84,9 +90,14 @@ type ReportsModel struct { lines []reportLine loaded bool - cursor int // index into lines + cursor int // index into lines; rebuild keeps it on the same row offset int // first visible line; see clampOffset + // open is the row whose entries reportsModeEntries lists, found again + // by its IDs after every reload, so the list never slides onto another + // row's entries. + open rowKey + entriesCursor int // index into the selected row's entries, in reportsModeEntries; see clampEntriesOffset entriesOffset int // scroll offset within entries; see clampEntriesOffset @@ -106,8 +117,6 @@ type ReportsModel struct { // now is the clock the presets and the today bar read; nil means // time.Now. Tests set it. now func() time.Time - - err string } func NewReports(database *db.DB) ReportsModel { @@ -199,22 +208,56 @@ func (m ReportsModel) loadCmd() tea.Cmd { } // rebuild makes the report for the range from the loaded entries, and its -// table rows: each client, then its projects. +// table rows: each client, then its projects. The cursor stays on the row +// it was on, found by its IDs, when that row is still there. func (m *ReportsModel) rebuild() { + var prev *rowKey + if l := m.selectedLine(); l != nil { + k := l.rowKey + prev = &k + } m.rep = report.Build(m.all, m.rng) - m.lines = m.lines[:0] + // A new slice, not lines[:0]: older copies of the model share the old + // one. + lines := make([]reportLine, 0, len(m.lines)) for _, c := range m.rep.Clients { - m.lines = append(m.lines, reportLine{client: true, clientID: c.ID, name: c.Name, clientName: c.Name, Counts: c.Counts}) + lines = append(lines, reportLine{rowKey: rowKey{client: true, clientID: c.ID}, name: c.Name, clientName: c.Name, Counts: c.Counts}) for _, p := range c.Projects { - m.lines = append(m.lines, reportLine{clientID: c.ID, projectID: p.ID, name: p.Name, clientName: c.Name, Counts: p.Counts}) + lines = append(lines, reportLine{rowKey: rowKey{clientID: c.ID, projectID: p.ID}, name: p.Name, clientName: c.Name, Counts: p.Counts}) } } - if m.cursor >= len(m.lines) { + m.lines = lines + if i := m.lineIndex(prev); i >= 0 { + m.cursor = i + } else if m.cursor >= len(m.lines) { m.cursor = max(0, len(m.lines)-1) } m.clampOffset() } +// lineIndex is the index of the row k names, or -1. +func (m ReportsModel) lineIndex(k *rowKey) int { + if k == nil { + return -1 + } + for i, l := range m.lines { + if l.rowKey == *k { + return i + } + } + return -1 +} + +// presetRange is the range a preset names as of the clock, or false for a +// custom range. +func (m ReportsModel) presetRange() (report.Range, bool) { + if m.preset == reportsPresetCustom { + return report.Range{}, false + } + r, err := report.Preset(string(m.preset), m.clock()) + return r, err == nil +} + // setPreset switches to a preset range as of now. func (m *ReportsModel) setPreset(p reportsPreset) { r, err := report.Preset(string(p), m.clock()) @@ -226,7 +269,6 @@ func (m *ReportsModel) setPreset(p reportsPreset) { func (m *ReportsModel) setRange(p reportsPreset, r report.Range) { m.preset, m.rng = p, r - m.cursor, m.offset = 0, 0 m.rebuild() } @@ -275,9 +317,18 @@ func (m ReportsModel) lineEntries(l *reportLine) []*model.Entry { return out } -// selectedEntries is the entries behind the selected row. +// openLine is the row whose entries the entries list shows, or nil when +// it's gone from the report. +func (m ReportsModel) openLine() *reportLine { + if i := m.lineIndex(&m.open); i >= 0 { + return &m.lines[i] + } + return nil +} + +// selectedEntries is the entries behind the open row. func (m ReportsModel) selectedEntries() []*model.Entry { - return m.lineEntries(m.selectedLine()) + return m.lineEntries(m.openLine()) } // selectedEntry is the entry under entriesCursor in the entries list, or @@ -337,15 +388,21 @@ var reportsKeys = reportsKeyMap{ func (m ReportsModel) Update(msg tea.Msg) (ReportsModel, tea.Cmd) { switch msg := msg.(type) { case reportEntriesMsg: - m.all, m.loaded, m.err = []*model.Entry(msg), true, "" - m.rebuild() - if m.mode == reportsModeEntries || m.mode == reportsModeEditEntry { - m.clampEntriesCursor() + var prevEntry int64 + if e := m.selectedEntry(); e != nil { + prevEntry = e.ID } - return m, nil + m.all, m.loaded = []*model.Entry(msg), true + // A preset is as of now, so a tab left open past midnight or into + // a new month moves on with the clock. + if r, ok := m.presetRange(); ok { + m.rng = r + } + m.rebuild() + return m.followEntries(prevEntry) case reportsOpenEditMsg: - return m.handleOpenEditEntry(msg), nil + return m.handleOpenEditEntry(msg) case tea.KeyMsg: switch m.mode { @@ -395,8 +452,9 @@ func (m ReportsModel) updateView(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { case key.Matches(msg, reportsKeys.Enter): // The entries behind the row get their own screen, with the // selected entry's details under them; e edits one from there. - if m.selectedLine() != nil { + if l := m.selectedLine(); l != nil { m.mode = reportsModeEntries + m.open = l.rowKey m.entriesCursor, m.entriesOffset = 0, 0 } case key.Matches(msg, reportsKeys.Custom): @@ -535,19 +593,44 @@ func (m ReportsModel) updateEntries(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { return m, nil } -// clampEntriesCursor keeps the entries cursor on an entry after a reload. -// When the row itself has gone (its last entry was moved out of it, say), -// it goes back to the report. -func (m *ReportsModel) clampEntriesCursor() { - n := len(m.selectedEntries()) - if n == 0 && m.mode == reportsModeEntries { - m.mode = reportsModeView - return +// errRowGone is the status line's note when the entries list's row has +// left the report. +const errRowGone = "That row has no entries in this range any more" + +// followEntries keeps the entries list on its row and entry after a +// reload: the cursor stays on the entry with ID prevEntry if it's still +// there. When the row itself has gone (its last entry moved to another +// project, say), the list closes and the status line says so. An open edit +// form stays, since it saves by the entry's ID, and closes to the report. +func (m ReportsModel) followEntries(prevEntry int64) (ReportsModel, tea.Cmd) { + if m.mode != reportsModeEntries && m.mode != reportsModeEditEntry { + return m, nil } - if m.entriesCursor >= n { - m.entriesCursor = max(0, n-1) + if m.openLine() == nil { + if m.mode == reportsModeEntries { + m.mode = reportsModeView + } + return m, ErrCmd(errRowGone) + } + es := m.selectedEntries() + m.entriesCursor = min(m.entriesCursor, max(0, len(es)-1)) + for i, e := range es { + if e.ID == prevEntry { + m.entriesCursor = i + } } m.clampEntriesOffset() + return m, nil +} + +// closeEditEntry leaves the edit form for the entries list, or for the +// report when the list's row has gone. +func (m ReportsModel) closeEditEntry() ReportsModel { + m.mode = reportsModeEntries + if m.openLine() == nil { + m.mode = reportsModeView + } + return m } // updateEditEntry handles keys in the Edit entry form. Field navigation, @@ -557,8 +640,7 @@ func (m ReportsModel) updateEditEntry(msg tea.KeyMsg) (ReportsModel, tea.Cmd) { action, cmd := updateTimerFormFields(&m.editForm, msg) switch action { case formCancel: - m.mode = reportsModeEntries - return m, nil + return m.closeEditEntry(), nil case formSubmit: return m.submitEditEntry(time.Now()) } @@ -576,7 +658,7 @@ func (m ReportsModel) submitEditEntry(now time.Time) (ReportsModel, tea.Cmd) { m.editForm.errs = nil closeForm, cmd := m.editForm.submitEdit(m.db, v, m.loadCmd()) if closeForm { - m.mode = reportsModeEntries + m = m.closeEditEntry() } return m, cmd } @@ -608,15 +690,14 @@ func (m ReportsModel) openEditEntryCmd(entryID int64) tea.Cmd { // handleOpenEditEntry fills the edit form from the entry msg names and // opens it. -func (m ReportsModel) handleOpenEditEntry(msg reportsOpenEditMsg) ReportsModel { +func (m ReportsModel) handleOpenEditEntry(msg reportsOpenEditMsg) (ReportsModel, tea.Cmd) { e := m.entryByID(msg.entryID) if e == nil { - m.err = "Entry not found" - return m + return m, ErrCmd("That entry is gone; it may have been deleted") } f := newTimerForm(msg.clients, msg.projects) f.fill(e) m.editForm = f m.mode = reportsModeEditEntry - return m + return m, nil } diff --git a/internal/ui/views/reports_export.go b/internal/ui/views/reports_export.go index 6815657..8a68a29 100644 --- a/internal/ui/views/reports_export.go +++ b/internal/ui/views/reports_export.go @@ -13,6 +13,7 @@ import ( "path/filepath" "strconv" "strings" + "syscall" "github.com/aliasproject/notch/internal/model" "github.com/aliasproject/notch/internal/report" @@ -38,18 +39,39 @@ func (m ReportsModel) exportCmd() tea.Cmd { // errNoEntries is exportCSV's answer for a range with nothing in it. var errNoEntries = errors.New("no finished entries in this range") -// exportCSV writes entries to a new file in exportDir named for the range, -// and returns its path. It never overwrites: when the name is taken it -// adds " (2)", " (3)"… before the extension. +// exportCSV writes entries to a new file named for the range in the +// first export folder it can write to, and returns its path. It never +// overwrites: when the name is taken it adds " (2)", " (3)"… before the +// extension. The file is private to the user (0600): it holds clients' +// earnings and notes. func exportCSV(entries []*model.Entry, r report.Range) (string, error) { if len(entries) == 0 { return "", errNoEntries } - dir, err := exportDir() + dirs, err := exportDirs() if err != nil { return "", err } - base := exportName(r) + var firstErr error + for _, dir := range dirs { + path, err := exportTo(dir, exportName(r), entries) + if err == nil { + return path, nil + } + if firstErr == nil { + firstErr = err + } + // A folder we can't write to (or a read-only disk): try the next. + if !errors.Is(err, fs.ErrPermission) && !errors.Is(err, syscall.EROFS) { + return "", err + } + } + return "", firstErr +} + +// exportTo writes entries to a new file base.csv in dir, or base (2).csv +// and so on when that's taken. +func exportTo(dir, base string, entries []*model.Entry) (string, error) { for n := 1; n < 1000; n++ { name := base + ".csv" if n > 1 { @@ -58,7 +80,7 @@ func exportCSV(entries []*model.Entry, r report.Range) (string, error) { path := filepath.Join(dir, name) // O_EXCL: fail rather than overwrite, even if another process // makes the file between the check and the write. - f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) if errors.Is(err, fs.ErrExist) { continue } @@ -97,10 +119,10 @@ func exportName(r report.Range) string { return "notch-" + r.From + "-to-" + r.To } -// exportDir is where exports go: the XDG download folder ($XDG_DOWNLOAD_DIR, -// or XDG_DOWNLOAD_DIR in user-dirs.dirs), else ~/Downloads, else the home -// folder, whichever exists first. -func exportDir() (string, error) { +// exportDirs is where exports can go, in order: the XDG download folder +// ($XDG_DOWNLOAD_DIR, or XDG_DOWNLOAD_DIR in user-dirs.dirs), then +// ~/Downloads, then the home folder; each only if it exists. +func exportDirs() ([]string, error) { home, homeErr := os.UserHomeDir() var candidates []string if d := os.Getenv("XDG_DOWNLOAD_DIR"); d != "" { @@ -112,22 +134,30 @@ func exportDir() (string, error) { if homeErr == nil { candidates = append(candidates, filepath.Join(home, "Downloads"), home) } + var out []string + seen := map[string]bool{} for _, d := range candidates { - if !filepath.IsAbs(d) { + if !filepath.IsAbs(d) || seen[d] { continue } + seen[d] = true if fi, err := os.Stat(d); err == nil && fi.IsDir() { - return d, nil + out = append(out, d) } } - if homeErr != nil { - return "", homeErr + if len(out) == 0 { + if homeErr != nil { + return nil, homeErr + } + return nil, fmt.Errorf("no downloads or home folder to save to") } - return "", fmt.Errorf("no downloads or home folder to save to") + return out, nil } // userDirsDownload reads XDG_DOWNLOAD_DIR from user-dirs.dirs in the XDG -// config folder, or "" if it isn't set there. +// config folder, or "" if it isn't set there. The file is shell syntax: +// comment lines, an optional export, and a value in double quotes, single +// quotes or none, maybe followed by a comment. func userDirsDownload(home string) string { cfg := os.Getenv("XDG_CONFIG_HOME") if cfg == "" || !filepath.IsAbs(cfg) { @@ -141,15 +171,36 @@ func userDirsDownload(home string) string { return "" } defer f.Close() + found := "" sc := bufio.NewScanner(f) for sc.Scan() { - k, v, ok := strings.Cut(strings.TrimSpace(sc.Text()), "=") + line := strings.TrimSpace(sc.Text()) + if strings.HasPrefix(line, "#") { + continue + } + line = strings.TrimSpace(strings.TrimPrefix(line, "export ")) + k, v, ok := strings.Cut(line, "=") if !ok || strings.TrimSpace(k) != "XDG_DOWNLOAD_DIR" { continue } - return expandHome(strings.Trim(strings.TrimSpace(v), `"`), home) + found = expandHome(shellWord(strings.TrimSpace(v)), home) // the last one wins, as in a shell + } + return found +} + +// shellWord is the first word of v: the text inside its quotes when it +// starts with " or ', else up to a space or #. +func shellWord(v string) string { + if v != "" && (v[0] == '"' || v[0] == '\'') { + if end := strings.IndexByte(v[1:], v[0]); end >= 0 { + return v[1 : 1+end] + } + return v[1:] + } + if i := strings.IndexAny(v, " \t#"); i >= 0 { + return v[:i] } - return "" + return v } // expandHome replaces a leading $HOME or ~ with home. diff --git a/internal/ui/views/reports_test.go b/internal/ui/views/reports_test.go index 756cbd6..3a1852d 100644 --- a/internal/ui/views/reports_test.go +++ b/internal/ui/views/reports_test.go @@ -249,8 +249,8 @@ func TestReports_StatCardsShowTheReport(t *testing.T) { // Each card's value is the report's, formatted. cards := m.statCards() for i, want := range []string{model.FormatDuration(time.Duration(rep.Seconds) * time.Second), formatMoney(rep.Earned), formatMoney(rep.Outstanding), formatMoney(rep.Unbilled)} { - if cards[i].value != want { - t.Errorf("card %s = %q, want %q", cards[i].label, cards[i].value, want) + if got := cards[i].value(20); got != want { + t.Errorf("card %s = %q, want %q", cards[i].label, got, want) } } } @@ -455,7 +455,7 @@ func TestReports_ShortTerminalKeepsTableRows(t *testing.T) { if m.compactChartRows() != 0 || strings.Contains(ansi.Strip(m.View()), "BY DAY") { t.Errorf("at 90×18 the bars should go:\n%s", ansi.Strip(m.View())) } - if m.rowsBudget() < minReportRows { + if m.rowsBudget() < theme.ReportMinRows { t.Errorf("rows budget %d", m.rowsBudget()) } if n := len(plainLines(m.View())); n > 16 { @@ -472,6 +472,7 @@ func TestReports_ShortTerminalKeepsTableRows(t *testing.T) { // ── Export ──────────────────────────────────────────────────────────────────── func TestReports_ExportCSV(t *testing.T) { + isolateExports(t) dir := t.TempDir() t.Setenv("XDG_DOWNLOAD_DIR", dir) m, _ := sampleReports(t, 140, 36) @@ -541,17 +542,17 @@ func TestReports_ExportNamesAndFolder(t *testing.T) { t.Setenv("HOME", home) t.Setenv("XDG_DOWNLOAD_DIR", "") t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) - if d, _ := exportDir(); d != home { + if d := firstExportDir(t); d != home { t.Errorf("with no Downloads, exports go home: %q", d) } os.Mkdir(filepath.Join(home, "Downloads"), 0o755) - if d, _ := exportDir(); d != filepath.Join(home, "Downloads") { + if d := firstExportDir(t); d != filepath.Join(home, "Downloads") { t.Errorf("~/Downloads: %q", d) } os.MkdirAll(filepath.Join(home, ".config"), 0o755) os.Mkdir(filepath.Join(home, "Téléchargements"), 0o755) os.WriteFile(filepath.Join(home, ".config", "user-dirs.dirs"), []byte("# xdg\nXDG_DOWNLOAD_DIR=\"$HOME/Téléchargements\"\n"), 0o644) - if d, _ := exportDir(); d != filepath.Join(home, "Téléchargements") { + if d := firstExportDir(t); d != filepath.Join(home, "Téléchargements") { t.Errorf("user-dirs.dirs: %q", d) } if got := tildePath(filepath.Join(home, "Downloads", "x.csv")); got != "~/Downloads/x.csv" { @@ -710,3 +711,219 @@ func TestEntryCols_RowWidthMatchesDivider(t *testing.T) { } } } + +func firstExportDir(t *testing.T) string { + t.Helper() + dirs, err := exportDirs() + if err != nil || len(dirs) == 0 { + t.Fatalf("exportDirs: %v %v", dirs, err) + } + return dirs[0] +} + +// ── Review round 1 ──────────────────────────────────────────────────────────── + +// A preset is as of now: a tab left open into a new week moves on at the +// next reload. A custom range stays put. +func TestReports_PresetsMoveWithTheClock(t *testing.T) { + isolateExports(t) + m, d := sampleReports(t, 140, 36) + later := time.Date(2026, 12, 8, 9, 0, 0, 0, time.Local) // the next Tuesday + m.now = func() time.Time { return later } + m, _ = m.Update(m.loadCmd()()) + if want := (report.Range{From: "2026-12-07", To: "2026-12-08"}); m.rng != want || m.rep.Range != want { + t.Errorf("This week after the clock moved on: %+v, want %+v", m.rng, want) + } + if !strings.Contains(plainLines(m.View())[0], "Dec 7 – Dec 8, 2026") { + t.Errorf("range line: %q", plainLines(m.View())[0]) + } + if msg := m.exportCmd()(); !strings.Contains(fmt.Sprint(msg), "Nothing to export") { + t.Errorf("the export should be for the new week, which is empty: %v", msg) + } + + m = pressReports(m, runeKey('f')) + m.fromInput.SetValue("2026-11-30") + m.toInput.SetValue("2026-12-01") + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + m.now = func() time.Time { return later.AddDate(0, 1, 0) } + m, _ = m.Update(NewReports(d).loadCmd()()) + if want := (report.Range{From: "2026-11-30", To: "2026-12-01"}); m.rng != want { + t.Errorf("a custom range moved with the clock: %+v", m.rng) + } +} + +// The cursor and the entries list follow their row by its IDs across a +// reload, not its index; when the row goes, the list closes and says so. +func TestReports_ReloadKeepsTheRowAndEntry(t *testing.T) { + m, d := sampleReports(t, 140, 36) + reload := func(m ReportsModel) (ReportsModel, tea.Cmd) { return m.Update(m.loadCmd()()) } + + // Website rebuild, then its older entry (Wednesday's). + m = pressReports(m, runeKey('j'), runeKey('j'), runeKey('j'), runeKey('j')) + if l := m.selectedLine(); l == nil || l.name != "Website rebuild" { + t.Fatalf("selected %+v", m.selectedLine()) + } + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}, runeKey('j')) + want := m.selectedEntry() + if want == nil || want.StartTime.Day() != 2 { + t.Fatalf("selected entry %+v", want) + } + + // A new client sorts first and shifts every row down by two. + c, _ := d.CreateClient("Aardvark", 50) + p, _ := d.CreateProject(c.ID, "Logo") + start := time.Date(2026, 12, 1, 8, 0, 0, 0, time.Local) + end := start.Add(time.Hour) + if _, err := d.AddEntry(p.ID, "Sketches", "", start, &end); err != nil { + t.Fatal(err) + } + m, cmd := reload(m) + if cmd != nil || m.mode != reportsModeEntries { + t.Fatalf("the list should stay open, mode %v", m.mode) + } + if l := m.openLine(); l == nil || l.name != "Website rebuild" { + t.Errorf("the list slid onto %+v", l) + } + if e := m.selectedEntry(); e == nil || e.ID != want.ID { + t.Errorf("the entry cursor slid onto %+v", e) + } + if l := m.selectedLine(); l == nil || l.name != "Website rebuild" { + t.Errorf("the table cursor slid onto %+v", l) + } + // e edits the entry that's selected, not its old index's. + m, cmd = m.Update(runeKey('e')) + m, _ = m.Update(cmd()) + if m.editForm.entryID != want.ID { + t.Errorf("e opened entry %d, want %d", m.editForm.entryID, want.ID) + } + m, _ = m.Update(tea.KeyMsg{Type: tea.KeyEsc}) + + // Booking app's one entry moves to Brand refresh: its row goes. + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEsc}, runeKey('j')) + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEsc}) + for m.selectedLine().name != "Booking app" { + m = pressReports(m, runeKey('k')) + } + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + e := m.selectedEntry() + var brand int64 + for _, l := range m.lines { + if l.name == "Brand refresh" { + brand = l.projectID + } + } + e2 := *e + e2.ProjectID, e2.Project = brand, nil + if err := d.UpdateEntry(&e2); err != nil { + t.Fatal(err) + } + m, cmd = reload(m) + if m.mode != reportsModeView { + t.Errorf("the list should close when its row goes, mode %v", m.mode) + } + if cmd == nil || cmd() != ErrMsg(errRowGone) { + t.Errorf("it should say why") + } +} + +// An entry gone by the time the edit form loads says so on the status +// line. +func TestReports_EditGoneEntrySaysSo(t *testing.T) { + m, _ := sampleReports(t, 140, 36) + m, cmd := m.Update(reportsOpenEditMsg{entryID: 9999}) + if m.mode == reportsModeEditEntry || cmd == nil { + t.Fatalf("mode %v cmd %v", m.mode, cmd) + } + if msg, ok := cmd().(ErrMsg); !ok || !strings.Contains(string(msg), "gone") { + t.Errorf("got %v", msg) + } +} + +func TestReports_ExportIsPrivateAndSkipsUnwritableFolders(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root writes anywhere") + } + home := t.TempDir() + locked := filepath.Join(home, "locked") + os.Mkdir(locked, 0o555) + t.Cleanup(func() { os.Chmod(locked, 0o755) }) + os.Mkdir(filepath.Join(home, "Downloads"), 0o755) + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_DOWNLOAD_DIR", locked) + + m, _ := sampleReports(t, 140, 36) + msg, ok := m.exportCmd()().(StatusMsg) + if !ok || !strings.Contains(string(msg), "~/Downloads/") { + t.Fatalf("export: %v", msg) + } + fi, err := os.Stat(filepath.Join(home, "Downloads", "notch-2026-11-30-to-2026-12-03.csv")) + if err != nil { + t.Fatal(err) + } + if perm := fi.Mode().Perm(); perm != 0o600 { + t.Errorf("mode %o, want 600", perm) + } +} + +func TestReports_UserDirsQuotesAndComments(t *testing.T) { + home := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + os.MkdirAll(filepath.Join(home, ".config"), 0o755) + for body, want := range map[string]string{ + "XDG_DOWNLOAD_DIR='$HOME/dl one'\n": home + "/dl one", + "# XDG_DOWNLOAD_DIR=\"$HOME/no\"\nXDG_DOWNLOAD_DIR=\"$HOME/dl\" # mine\n": home + "/dl", + "export XDG_DOWNLOAD_DIR=$HOME/bare # note\n": home + "/bare", + "XDG_MUSIC_DIR=\"$HOME/Music\"\n": "", + } { + os.WriteFile(filepath.Join(home, ".config", "user-dirs.dirs"), []byte(body), 0o644) + if got := userDirsDownload(home); got != want { + t.Errorf("%q: got %q, want %q", body, got, want) + } + } +} + +// Amounts too wide for their cell drop the cents, then go compact (as in +// the entries list's EARNED); they're never cut with an ellipsis. +func TestReports_LargeAmountsAreNeverCut(t *testing.T) { + for _, w := range []int{64, 90} { + d := newTestDB(t) + c, _ := d.CreateClient("Megacorp", 912_345.67) + p, _ := d.CreateProject(c.ID, "Merger") + start := time.Date(2026, 12, 1, 9, 0, 0, 0, time.Local) + end := start.Add(3 * time.Hour) + if _, err := d.AddEntry(p.ID, "Due diligence", "", start, &end); err != nil { + t.Fatal(err) + } + m := NewReports(d) + m.now = func() time.Time { return reportsNow } + m.SetSize(w, 28) + m, _ = m.Update(m.loadCmd()()) + m = pressReports(m, runeKey('w')) + view := ansi.Strip(m.View()) + if regexp.MustCompile(`[\d$,.]…`).MatchString(view) { + t.Errorf("%d: an amount was cut:\n%s", w, view) + } + // The table's EARNED drops the cents. + for _, want := range []string{"$2,737,037 "} { + if !strings.Contains(view, want) { + t.Errorf("%d: missing %q:\n%s", w, want, view) + } + } + m = pressReports(m, tea.KeyMsg{Type: tea.KeyEnter}) + if v := ansi.Strip(m.View()); regexp.MustCompile(`[\d$,.]…`).MatchString(v) || !strings.Contains(v, "$2.7M") { + t.Errorf("%d: entries view:\n%s", w, v) + } + } +} + +// isolateExports points every folder an export could use at a temp dir, so +// a test (or a broken build of one) never writes to the real downloads. +func isolateExports(t *testing.T) string { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_DOWNLOAD_DIR", home) + return home +} diff --git a/internal/ui/views/reports_view.go b/internal/ui/views/reports_view.go index 2a6f104..28af6f0 100644 --- a/internal/ui/views/reports_view.go +++ b/internal/ui/views/reports_view.go @@ -3,7 +3,7 @@ package views // Drawing the Reports tab (ALI-2618). From theme.WideMin columns, and tall // enough, the hours bars sit left of the table, as on the 140×40 board; // narrower or shorter terminals stack them, with shorter bars, and drop -// the bars when the table would get fewer than minReportRows rows. +// the bars when the table would get fewer than tui-report-min-rows rows. // // Colour is never the only signal: the on range chip is a filled block, // each bar has its hours written under it and today's day name is bold, @@ -21,20 +21,12 @@ import ( "github.com/charmbracelet/lipgloss" ) -// Fixed rows of the screen's top: the range chips and a blank, then the -// stat cards and a blank. Wide cards are boxes (two borders and three -// lines); compact ones drop the top and bottom borders. +// Rows of the screen's top: the range chips and a blank, then the stat +// cards and a blank. Wide cards are boxes (their lines between a top and a +// bottom border); compact ones drop the borders. const ( - reportCardRows = 5 - reportCardRowsCompact = 3 - reportTopRows = 2 + reportCardRows + 1 - reportTopRowsCompact = 2 + reportCardRowsCompact + 1 - // reportTableFixed is the table's title, column titles and rule above - // the rows, and the rule and total below them. - reportTableFixed = 5 - // minReportRows is the fewest table rows the layout keeps; the bars go - // before the table gets fewer. - minReportRows = 3 + reportTopRows = 2 + statCardLines + 2 + 1 + reportTopRowsCompact = 2 + statCardLines + 1 ) // barsRows is the chart's height at a bar height: its title, the bars, and @@ -49,21 +41,21 @@ func (m ReportsModel) innerHeight() int { return max(1, m.height-2) } // note. func (m ReportsModel) wide() bool { return m.width >= theme.WideMin && - m.innerHeight()-reportTopRows >= max(barsRows(theme.BarRows)+2, reportTableFixed+minReportRows) + m.innerHeight()-reportTopRows >= max(barsRows(theme.BarRows)+2, m.tableFixed()+theme.ReportMinRows) } // compactChartRows is what the stacked bars take, with the blank under // them, or 0 when the table needs the room. func (m ReportsModel) compactChartRows() int { rows := barsRows(theme.BarRowsCompact) + 1 - if m.compactRowsWith(rows) < minReportRows { + if m.compactRowsWith(rows) < theme.ReportMinRows { return 0 } return rows } func (m ReportsModel) compactRowsWith(chart int) int { - rows := m.innerHeight() - reportTopRowsCompact - chart - reportTableFixed + rows := m.innerHeight() - reportTopRowsCompact - chart - m.tableFixed() if m.running() != nil { rows-- // the running note under the table } @@ -73,7 +65,7 @@ func (m ReportsModel) compactRowsWith(chart int) int { // rowsBudget is how many table rows fit. func (m ReportsModel) rowsBudget() int { if m.wide() { - return max(1, m.innerHeight()-reportTopRows-reportTableFixed) + return max(1, m.innerHeight()-reportTopRows-m.tableFixed()) } return max(1, m.compactRowsWith(m.compactChartRows())) } @@ -156,6 +148,17 @@ func (m ReportsModel) renderReport() string { // runningNote says why the running timer's time isn't in the report. const runningNote = "Running timer not counted until it stops." +// ── Numbers ─────────────────────────────────────────────────────────────────── + +// fitHours renders secs as h:mm:ss in at most w cells, or as whole hours +// ("1235h") when that's too wide; like fitMoney (money.go), it never cuts. +func fitHours(secs int64, w int) string { + if s := model.FormatDuration(time.Duration(secs) * time.Second); lipgloss.Width(s) <= w { + return s + } + return fmt.Sprintf("%.0fh", float64(secs)/3600) +} + // ── Range chips ─────────────────────────────────────────────────────────────── type reportsChip struct { @@ -217,91 +220,102 @@ func rangeLabel(r report.Range) string { // ── Stat cards ──────────────────────────────────────────────────────────────── type statCard struct { - label, value, sub, short string // short: sub for a narrow card - fg lipgloss.Color + label string + value func(w int) string // fitted to w cells + sub func(w int) string + fg lipgloss.Color +} + +// cardText is what a card shows, a line each: its label, its value and +// the line under the value. +type cardText [3]seg + +// statCardLines is how many lines of text a card has. +const statCardLines = len(cardText{}) + +func (c statCard) text(inner int) cardText { + return cardText{ + {s: fit(c.label, inner), fg: cSubtle, bold: true}, + {s: fit(c.value(inner), inner), fg: c.fg, bold: true}, + {s: fit(c.sub(inner), inner), fg: cSubtle}, + } +} + +// countText is "6 entries", or just "6" when that doesn't fit w. +func countText(n, w int) string { + if s := fmt.Sprintf("%d %s", n, plural(n, "entry", "entries")); lipgloss.Width(s) <= w { + return s + } + return fmt.Sprint(n) } // statCards are the four cards, from report.Report: the hours, what they // earned, what's invoiced and not paid, and what isn't invoiced yet. func (m ReportsModel) statCards() []statCard { rep := m.rep - avg := "avg —" - if rep.Seconds > 0 { - avg = "avg " + formatMoney(rep.AverageRate) + "/h" - } + money := func(x float64) func(int) string { return func(w int) string { return fitMoney(x, w) } } return []statCard{ - {label: "HOURS", value: model.FormatDuration(time.Duration(rep.Seconds) * time.Second), - sub: fmt.Sprintf("%d %s", rep.Entries, plural(rep.Entries, "entry", "entries")), fg: cHighlight}, - {label: "EARNED", value: formatMoney(rep.Earned), sub: avg, fg: cGreen}, - {label: "OUTSTANDING", value: formatMoney(rep.Outstanding), sub: "invoiced, not paid", short: "not paid yet", fg: cAmber}, - {label: "UNBILLED", value: formatMoney(rep.Unbilled), - sub: fmt.Sprintf("%d %s", rep.UnbilledEntries, plural(rep.UnbilledEntries, "entry", "entries")), fg: cText}, + {label: "HOURS", fg: cHighlight, + value: func(w int) string { return fitHours(rep.Seconds, w) }, + sub: func(w int) string { return countText(rep.Entries, w) }}, + {label: "EARNED", fg: cGreen, value: money(rep.Earned), + sub: func(w int) string { + if rep.Seconds == 0 { + return "avg —" + } + if s := "avg " + fitRate(rep.AverageRate, w-4); lipgloss.Width(s) <= w { + return s + } + return fitRate(rep.AverageRate, w) + }}, + {label: "OUTSTANDING", fg: cAmber, value: money(rep.Outstanding), + sub: func(w int) string { + if s := "invoiced, not paid"; lipgloss.Width(s) <= w { + return s + } + return "not paid yet" + }}, + {label: "UNBILLED", fg: cText, value: money(rep.Unbilled), + sub: func(w int) string { return countText(rep.UnbilledEntries, w) }}, } } // renderCards draws the four cards across w, tui-card-gap apart: boxed when -// wide, and as three lines after a rule when compact. +// wide, and as their lines after a rule when compact. func (m ReportsModel) renderCards(w int, boxed bool) []string { cards := m.statCards() cw := max(6, (w-(len(cards)-1)*theme.CardGap)/len(cards)) - if !boxed { - return renderCardsCompact(cards, cw, w) - } - inner := cw - 4 // the borders and a space inside each - out := make([]string, reportCardRows) + side := lipgloss.Width(boxSide().s) + pad := seg{s: strings.Repeat(" ", theme.CardPad)} gap := seg{s: strings.Repeat(" ", theme.CardGap)} + rows := statCardLines + inner := cw - side - theme.CardPad + if boxed { + rows += 2 // the top and bottom borders + inner = cw - 2*(side+theme.CardPad) + } + out := make([]string, rows) for i, c := range cards { - sub := c.sub - if c.short != "" && len([]rune(sub)) > inner { - sub = c.short + text := c.text(inner) + lines := make([][]seg, 0, rows) + if boxed { + lines = append(lines, []seg{{s: "╭" + strings.Repeat("─", cw-2*side) + "╮", fg: cBorder}}) } - rows := [3]seg{ - {s: fit(c.label, inner), fg: cSubtle, bold: true}, - {s: fit(c.value, inner), fg: c.fg, bold: true}, - {s: fit(sub, inner), fg: cSubtle}, - } - edge := seg{s: "╭" + strings.Repeat("─", cw-2) + "╮", fg: cBorder} - foot := seg{s: "╰" + strings.Repeat("─", cw-2) + "╯", fg: cBorder} - if i > 0 { - out[0] += renderSegs(cBg, gap) - out[4] += renderSegs(cBg, gap) - } - out[0] += renderSegs(cBg, edge) - out[4] += renderSegs(cBg, foot) - for r, s := range rows { - if i > 0 { - out[r+1] += renderSegs(cBg, gap) + for _, t := range text { + l := []seg{boxSide(), pad, t} + if boxed { + l = append(l, pad, boxSide()) } - out[r+1] += renderSegs(cBg, boxSide(), seg{s: " "}, s, seg{s: " "}, boxSide()) + lines = append(lines, l) } - } - for i := range out { - out[i] = padTo(out[i], w) - } - return out -} - -// renderCardsCompact draws the cards as three lines each, after a rule in -// border, cw wide. -func renderCardsCompact(cards []statCard, cw, w int) []string { - inner := cw - 2 // the rule and a space - out := make([]string, reportCardRowsCompact) - gap := seg{s: strings.Repeat(" ", theme.CardGap)} - for i, c := range cards { - sub := c.sub - if c.short != "" && len([]rune(sub)) > inner { - sub = c.short + if boxed { + lines = append(lines, []seg{{s: "╰" + strings.Repeat("─", cw-2*side) + "╯", fg: cBorder}}) } - rows := [3]seg{ - {s: fit(c.label, inner), fg: cSubtle, bold: true}, - {s: fit(c.value, inner), fg: c.fg, bold: true}, - {s: fit(sub, inner), fg: cSubtle}, - } - for r, s := range rows { + for r, l := range lines { if i > 0 { out[r] += renderSegs(cBg, gap) } - out[r] += renderSegs(cBg, boxSide(), seg{s: " "}, s) + out[r] += renderSegs(cBg, l...) } } for i := range out { @@ -489,26 +503,62 @@ func reportRowSegs(w int, name string, nameSeg seg, hours, inv, paid, earned seg return []seg{nameSeg, hours, inv, paid, earned, {s: strings.Repeat(" ", theme.ReportTrail)}} } +// earnedCell is the EARNED column's text: the amount fitted to the column +// with a gap before it, or "—" for none. func earnedCell(x float64) string { + if x == 0 { + return "—" + } + return fitMoney(x, theme.ReportColEarned-1) +} + +// moneyOrDash is x in full, or "—" for none. +func moneyOrDash(x float64) string { if x == 0 { return "—" } return formatMoney(x) } -// renderTable is the BY CLIENT AND PROJECT table, w wide: its title, the -// column titles, the window of client and project rows, and the total. -func (m ReportsModel) renderTable(w int) []string { +// hoursCell is the HOURS column's text, fitted with a gap before it. +func hoursCell(secs int64) string { return fitHours(secs, theme.ReportColHours-1) } + +// tableHead is the table's lines above its rows: the title, the column +// titles and a rule, with ▲ and ▼ when rows are hidden. +func (m ReportsModel) tableHead(w int, above, below bool) []string { head := func(s string) seg { return seg{s: s, fg: cSubtle, bold: true} } lead := seg{s: strings.Repeat(" ", theme.Gutter)} - out := []string{ + return []string{ renderSegs(cBg, seg{s: fit("BY CLIENT AND PROJECT", w), fg: cSubtle, bold: true}), spread(w, cBg, append([]seg{lead}, reportRowSegs(w, "NAME", head(""), head("HOURS"), head("INVOICED"), head("PAID"), head("EARNED"))...), nil), + rule(w, above, below), } +} + +// tableFoot is the table's lines under its rows: a rule and the total. +func (m ReportsModel) tableFoot(w int) []string { + rep := m.rep + total := reportRowSegs(w, "Total", seg{bold: true}, + seg{s: hoursCell(rep.Seconds), bold: true}, + seg{s: fmt.Sprintf("%d/%d", rep.Invoiced, rep.Entries), fg: cAccent, bold: true}, + seg{s: fmt.Sprintf("%d/%d", rep.Paid, rep.Entries), fg: cGreen, bold: true}, + seg{s: earnedCell(rep.Earned), bold: true}) + return []string{rule(w, false, false), spread(w, cBg, append([]seg{{s: strings.Repeat(" ", theme.Gutter)}}, total...), nil)} +} + +// tableFixed is how many of the table's lines aren't rows. +func (m ReportsModel) tableFixed() int { + return len(m.tableHead(1, false, false)) + len(m.tableFoot(1)) +} + +// renderTable is the BY CLIENT AND PROJECT table, w wide: its title, the +// column titles, the window of client and project rows, and the total. +func (m ReportsModel) renderTable(w int) []string { + lead := seg{s: strings.Repeat(" ", theme.Gutter)} budget := m.rowsBudget() start := m.offset end := min(len(m.lines), start+budget) - out = append(out, rule(w, start > 0, end < len(m.lines))) + out := m.tableHead(w, start > 0, end < len(m.lines)) if len(m.lines) == 0 { out = append(out, renderSegs(cBg, lead, seg{s: fit(truncate("No finished time in this range.", w-theme.Gutter), w-theme.Gutter), fg: cSubtle})) } @@ -520,13 +570,7 @@ func (m ReportsModel) renderTable(w int) []string { out = append(out, blankLine(w)) } } - rep := m.rep - total := reportRowSegs(w, "Total", seg{bold: true}, - seg{s: model.FormatDuration(time.Duration(rep.Seconds) * time.Second), bold: true}, - seg{s: fmt.Sprintf("%d/%d", rep.Invoiced, rep.Entries), fg: cAccent, bold: true}, - seg{s: fmt.Sprintf("%d/%d", rep.Paid, rep.Entries), fg: cGreen, bold: true}, - seg{s: earnedCell(rep.Earned), bold: true}) - return append(out, rule(w, false, false), spread(w, cBg, append([]seg{lead}, total...), nil)) + return append(out, m.tableFoot(w)...) } // renderLine draws a client row (bold) or a project row (indented, dim). @@ -545,7 +589,7 @@ func (m ReportsModel) renderLine(l reportLine, sel bool, w int) string { nameSeg, numFg, bold = seg{fg: cDim, bold: sel}, cDim, false } segs := reportRowSegs(w, name, nameSeg, - seg{s: model.FormatDuration(time.Duration(l.Seconds) * time.Second), fg: numFg, bold: bold}, + seg{s: hoursCell(l.Seconds), fg: numFg, bold: bold}, seg{s: fmt.Sprintf("%d/%d", l.Invoiced, l.Entries), fg: cAccent}, seg{s: fmt.Sprintf("%d/%d", l.Paid, l.Entries), fg: cGreen}, seg{s: earnedCell(l.Earned), fg: numFg, bold: bold}) @@ -584,20 +628,27 @@ func (m ReportsModel) viewCustom(w, h int) []string { // ── Entries behind a row ────────────────────────────────────────────────────── // entryCols returns the entries table's column widths, for both its drawing -// and its scrolling. TASK takes what's left. +// and its scrolling: each fixed column is its widest usual value plus the +// cells' padding, and TASK takes what's left. A longer value is fitted +// (see fitHours and fitMoney), never cut mid-number. func (m ReportsModel) entryCols() (date, task, dur, earned, stat int) { - date, dur, earned, stat = 14, 12, 12, 12 - task = usableWidth(m.width) - (theme.Gutter + date + dur + earned + stat) - if task < 20 { - // Narrow terminal: tighten the fixed columns to their widest - // content ("Sep 10, 2026", "12:34:56", "$1234.56", "◐ invoiced") - // before squeezing TASK, so no row wraps. - date, dur, earned, stat = 13, 10, 10, 11 - task = max(8, usableWidth(m.width)-(theme.Gutter+date+dur+earned+stat)) - } + pad := StyleTableRow.GetHorizontalFrameSize() + date = lipgloss.Width("Sep 30, 2026") + pad + dur = lipgloss.Width(model.FormatDuration(99*time.Hour+59*time.Minute+59*time.Second)) + pad + earned = lipgloss.Width(formatMoney(9999.99)) + pad + stat = lipgloss.Width(theme.GlyphInvoiced+" invoiced") + pad + task = max(1, usableWidth(m.width)-(theme.Gutter+date+dur+earned+stat)) return date, task, dur, earned, stat } +// entryEarned is an entry's earnings fitted to w, or "—" with no rate. +func entryEarned(e *model.Entry, now time.Time, w int) string { + if x, ok := earned(e, now); ok { + return fitMoney(x, w) + } + return "—" +} + // renderEntryDetail shows the selected entry's start and end, notes and // status, like the Timers tab's detail. func (m ReportsModel) renderEntryDetail(e *model.Entry) string { @@ -641,7 +692,7 @@ func (m *ReportsModel) clampEntriesOffset() { // renderEntriesView is the entries behind the selected row, newest first, // with the selected entry's details under them. func (m ReportsModel) renderEntriesView() string { - l := m.selectedLine() + l := m.openLine() if l == nil { return m.renderReport() } @@ -651,7 +702,7 @@ func (m ReportsModel) renderEntriesView() string { } header := StyleTitle.Render(title) + StyleMuted.Render(" · ") + - StyleMuted.Render(model.FormatDuration(time.Duration(l.Seconds)*time.Second)+" · "+earnedCell(l.Earned)+" · "+rangeLabel(m.rng)) + StyleMuted.Render(model.FormatDuration(time.Duration(l.Seconds)*time.Second)+" · "+moneyOrDash(l.Earned)+" · "+rangeLabel(m.rng)) entries := m.selectedEntries() if len(entries) == 0 { return header + "\n\n" + StyleMuted.Render("No entries for this period.") @@ -671,6 +722,7 @@ func (m ReportsModel) renderEntriesView() string { end := min(len(entries), start+m.entriesRowsBudget()) rows := []string{hdr, rule(totalW, start > 0, end < len(entries))} now := m.clock() + pad := StyleTableRow.GetHorizontalFrameSize() for i := start; i < end; i++ { e := entries[i] sel := i == m.entriesCursor @@ -682,8 +734,8 @@ func (m ReportsModel) renderEntriesView() string { rows = append(rows, RowPrefix(sel)+ base.Width(colDate).Render(e.StartTime.Local().Format("Jan 2, 2006"))+ base.Width(colTask).Render(truncate(e.Task, colTask-3))+ - base.Width(colDur).Align(lipgloss.Right).Render(model.FormatDuration(e.Duration()))+ - base.Width(colEarned).Align(lipgloss.Right).Render(earnedText(e, now))+ + base.Width(colDur).Align(lipgloss.Right).Render(fitHours(int64(e.Duration()/time.Second), colDur-pad))+ + base.Width(colEarned).Align(lipgloss.Right).Render(entryEarned(e, now, colEarned-pad))+ lipgloss.NewStyle().Foreground(statFg).Background(rowBg).Padding(0, 1).Width(colStatus).Render(statText)) } detail := "" From aff033d5dc476c32cd46f98829a3d4b84c760969 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 10:41:26 -0700 Subject: [PATCH 3/4] Rename the Reports entries header's amountOrDash after the merge (ALI-2618) The Clients tab (ALI-2617) has its own moneyOrDash(x, rate, w), so the Reports one, which shows an amount in full or a dash, is amountOrDash. --- internal/ui/views/reports_view.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/ui/views/reports_view.go b/internal/ui/views/reports_view.go index 28af6f0..644490a 100644 --- a/internal/ui/views/reports_view.go +++ b/internal/ui/views/reports_view.go @@ -512,8 +512,8 @@ func earnedCell(x float64) string { return fitMoney(x, theme.ReportColEarned-1) } -// moneyOrDash is x in full, or "—" for none. -func moneyOrDash(x float64) string { +// amountOrDash is x in full, or "—" for none. +func amountOrDash(x float64) string { if x == 0 { return "—" } @@ -702,7 +702,7 @@ func (m ReportsModel) renderEntriesView() string { } header := StyleTitle.Render(title) + StyleMuted.Render(" · ") + - StyleMuted.Render(model.FormatDuration(time.Duration(l.Seconds)*time.Second)+" · "+moneyOrDash(l.Earned)+" · "+rangeLabel(m.rng)) + StyleMuted.Render(model.FormatDuration(time.Duration(l.Seconds)*time.Second)+" · "+amountOrDash(l.Earned)+" · "+rangeLabel(m.rng)) entries := m.selectedEntries() if len(entries) == 0 { return header + "\n\n" + StyleMuted.Render("No entries for this period.") From 9a4864aa0d8af37077d089d2b1073b222ee3e9c9 Mon Sep 17 00:00:00 2001 From: Michael Aguiar Date: Fri, 4 Dec 2026 10:43:56 -0700 Subject: [PATCH 4/4] Drop the removed fourth tab from the tab-switch test Tab 4 no longer exists after the Clients fold, so pressing 4 did nothing and that iteration tested nothing. --- internal/ui/app_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/ui/app_test.go b/internal/ui/app_test.go index 2c00d37..bb17183 100644 --- a/internal/ui/app_test.go +++ b/internal/ui/app_test.go @@ -579,7 +579,7 @@ func TestTabSwitch_ClosesDetails(t *testing.T) { u, _ := m.Update(msg) m = u.(AppModel) } - for _, k := range []rune{'1', '2', '3', '4'} { + for _, k := range []rune{'1', '2', '3'} { step(runeKey('1')) step(tea.KeyMsg{Type: tea.KeyEnter}) if !strings.Contains(plainText(m.View()), "╭─ Entry") {