diff --git a/README.md b/README.md index 7786672..44eaf29 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,24 @@ Times are shown and entered in the server's `TZ` (UTC in Docker unless you set i times without an offset are read in that zone too. Raise `BODY_SIZE_LIMIT` if a large export is rejected with 413. +## Report + +**Report** shows where a month went: an ECharts Sankey from source (Calendar, Timer, Manual, +Import) to category to project, with hours on each link (entries without a project appear by +title), and a table of hours per category and project. Pick a month, and use _Export CSV_ to +download the month's entries with their category and hours. Like **Time**, a month holds the +entries that start in it; a running timer counts once it stops. + +Categories and their colors are set on **Settings**, along with rules that assign them. A rule +matches an entry's source, or its project or title by keyword (case-insensitive substring) or +regular expression (case-insensitive). Rules are tried in order and the first match wins; entries +no rule matches are _Uncategorized_. Move a rule up or down to change its precedence. + +Calendar blocks often overlap time you tracked (timer, manual or imported entries). The report +shows how much overlaps. By default both are counted; tick _Tracked time wins over calendar_ to +count overlapping time only for the tracked entry. The CSV has the entry's full hours and the +hours counted with the chosen option. + ## Capture API Send a dump from anywhere with `POST /api/dumps` and `Authorization: Bearer $DUMPDOWN_API_TOKEN`. diff --git a/package-lock.json b/package-lock.json index 1235d54..53bbf65 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "0.0.1", "dependencies": { "better-sqlite3": "^13.2.0", + "echarts": "^6.1.0", "ical.js": "^2.2.1", "zod": "^4.6.7" }, @@ -1324,6 +1325,16 @@ "dev": true, "license": "MIT" }, + "node_modules/echarts": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/echarts/-/echarts-6.1.0.tgz", + "integrity": "sha512-q0yaFPggC9FUdsWH4blavRWFmxdrIodbkoKNAjJudAI6CA9gNPxHtV2RcZNEepZVlk4yvBYkOkbk6HIVpIyHZA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "2.3.0", + "zrender": "6.1.0" + } + }, "node_modules/es-module-lexer": { "version": "2.3.2", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", @@ -2928,6 +2939,12 @@ "typescript": ">=4.8.4" } }, + "node_modules/tslib": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz", + "integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg==", + "license": "0BSD" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", @@ -3252,6 +3269,15 @@ "funding": { "url": "https://github.com/sponsors/colinhacks" } + }, + "node_modules/zrender": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/zrender/-/zrender-6.1.0.tgz", + "integrity": "sha512-oEGMDB6pOP2S6OwRR4PdVv610zrjnA3Bh+JnSG12fYJlBKjtNAoEb5fSUoCOOINlH96I2fU38/A2UpRKs67xYQ==", + "license": "BSD-3-Clause", + "dependencies": { + "tslib": "2.3.0" + } } } } diff --git a/package.json b/package.json index 6d56c27..d8ff872 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ }, "dependencies": { "better-sqlite3": "^13.2.0", + "echarts": "^6.1.0", "ical.js": "^2.2.1", "zod": "^4.6.7" } diff --git a/src/lib/components/Placeholder.svelte b/src/lib/components/Placeholder.svelte deleted file mode 100644 index 399e145..0000000 --- a/src/lib/components/Placeholder.svelte +++ /dev/null @@ -1,19 +0,0 @@ - - - - {item.label} · dumpdown - - -

{item.label}

-

{item.description}

-

Coming soon.

- - diff --git a/src/lib/components/Sankey.svelte b/src/lib/components/Sankey.svelte new file mode 100644 index 0000000..1dbe48c --- /dev/null +++ b/src/lib/components/Sankey.svelte @@ -0,0 +1,42 @@ + + + + + diff --git a/src/lib/report.spec.ts b/src/lib/report.spec.ts new file mode 100644 index 0000000..5cd6151 --- /dev/null +++ b/src/lib/report.spec.ts @@ -0,0 +1,315 @@ +import { describe, expect, it } from 'vitest'; +import { + buildReport, + categorizer, + resolveOverlaps, + ruleError, + sankeyHeight, + toHours, + type Category, + type CategoryRule, + type ReportEntry, + type Source +} from './report'; + +let nextId = 1; + +/** An entry on 2026-11-02 from `start` to `end` (`HH:MM`, UTC). */ +function entry( + source: Source, + start: string, + end: string, + title = '', + project: string | null = null +): ReportEntry { + return { + id: nextId++, + source, + start_at: `2026-11-02T${start}:00.000Z`, + end_at: `2026-11-02T${end}:00.000Z`, + title, + project + }; +} + +let nextRuleId = 1; +function rule( + category_id: number, + field: CategoryRule['field'], + pattern: string, + mode: CategoryRule['mode'] = 'keyword' +): CategoryRule { + return { id: nextRuleId++, category_id, field, mode, pattern }; +} + +const HOUR = 3_600_000; + +describe('ruleError', () => { + it('accepts keywords, valid regexes and known sources', () => { + expect(ruleError('title', 'keyword', 'standup')).toBeNull(); + expect(ruleError('project', 'regex', '^acme\\b')).toBeNull(); + expect(ruleError('source', 'keyword', 'timer')).toBeNull(); + }); + + it('rejects empty patterns, invalid regexes and unknown sources', () => { + expect(ruleError('title', 'keyword', ' ')).toBe('Enter a pattern'); + expect(ruleError('title', 'regex', '(unclosed')).toBe('Enter a valid regular expression'); + expect(ruleError('source', 'keyword', 'email')).toMatch(/^Choose one of/); + }); +}); + +describe('categorizer', () => { + const e = (source: Source, title: string, project: string | null = null) => ({ + source, + title, + project + }); + + it('uses the first matching rule, in order', () => { + const categoryOf = categorizer([ + rule(1, 'title', 'standup'), + rule(2, 'project', 'acme'), + rule(3, 'source', 'calendar') + ]); + expect(categoryOf(e('calendar', 'Daily Standup', 'Acme'))).toBe(1); + expect(categoryOf(e('timer', 'Fix bug', 'ACME website'))).toBe(2); + expect(categoryOf(e('calendar', 'Dentist'))).toBe(3); + expect(categoryOf(e('timer', 'Dentist'))).toBeNull(); + }); + + it('matches regexes case-insensitively and never matches invalid ones', () => { + const categoryOf = categorizer([ + rule(1, 'title', '(broken', 'regex'), + rule(2, 'title', '^(1:1|one on one)\\b', 'regex'), + rule(3, 'project', '^$', 'regex') + ]); + expect(categoryOf(e('calendar', 'One on One with Sam'))).toBe(2); + expect(categoryOf(e('calendar', 'Prep 1:1'))).toBe(3); + expect(categoryOf(e('calendar', 'Prep 1:1', 'Ops'))).toBeNull(); + }); + + it('matches a source rule only on the exact source', () => { + const categoryOf = categorizer([rule(1, 'source', 'import')]); + expect(categoryOf(e('import', 'x'))).toBe(1); + expect(categoryOf(e('timer', 'import'))).toBeNull(); + }); + + it('leaves everything uncategorized without rules', () => { + expect(categorizer([])(e('timer', 'anything'))).toBeNull(); + }); +}); + +describe('resolveOverlaps', () => { + const counted = (entries: ReportEntry[], trackedWins: boolean) => { + const result = resolveOverlaps(entries, trackedWins); + return { + counted: result.entries.map((r) => r.countedMs / 60_000), + overlap: result.overlapMs / 60_000 + }; + }; + + it('counts overlapping time twice unless tracked time wins', () => { + const entries = [entry('calendar', '09:00', '10:00'), entry('timer', '09:30', '10:30')]; + expect(counted(entries, false)).toEqual({ counted: [60, 60], overlap: 30 }); + expect(counted(entries, true)).toEqual({ counted: [30, 60], overlap: 30 }); + }); + + it('drops a fully covered block and splits one with tracked time in the middle', () => { + const entries = [ + entry('calendar', '09:00', '10:00'), + entry('calendar', '12:00', '14:00'), + entry('timer', '08:00', '11:00'), + entry('manual', '12:30', '13:00') + ]; + expect(counted(entries, true)).toEqual({ counted: [0, 90, 180, 30], overlap: 90 }); + }); + + it('does not subtract time covered by two tracked entries twice', () => { + const entries = [ + entry('calendar', '09:00', '11:00'), + entry('timer', '09:00', '10:00'), + entry('import', '09:30', '10:30') + ]; + expect(counted(entries, true)).toEqual({ counted: [30, 60, 60], overlap: 90 }); + }); + + it('ignores entries that only touch and calendar blocks overlapping each other', () => { + const entries = [ + entry('calendar', '09:00', '10:00'), + entry('calendar', '09:30', '10:00'), + entry('timer', '10:00', '11:00') + ]; + expect(counted(entries, true)).toEqual({ counted: [60, 30, 60], overlap: 0 }); + }); +}); + +describe('buildReport', () => { + const categories: Category[] = [ + { id: 1, name: 'Meetings', color: '#2a78d6' }, + { id: 2, name: 'Client work', color: '#eb6834' }, + { id: 3, name: 'Unused', color: '#1baf7a' } + ]; + const rules = [ + rule(1, 'source', 'calendar'), + rule(2, 'project', 'acme'), + // A rule pointing to a category that no longer exists falls back to Uncategorized. + rule(99, 'title', 'lost') + ]; + const entries = [ + entry('calendar', '09:00', '10:00', 'Standup'), + entry('timer', '09:30', '11:30', 'Build', 'Acme'), + entry('manual', '13:00', '13:45', 'Invoice', 'Acme'), + entry('timer', '14:00', '15:00', 'lost keys'), + entry('import', '15:00', '15:30', '') + ]; + + it('totals categories and their projects, falling back to titles', () => { + const report = buildReport(entries, categories, rules); + expect(report.totalMs).toBe(5.25 * HOUR); + expect(report.overlapMs).toBe(0.5 * HOUR); + expect(report.totals).toEqual([ + { + id: 2, + name: 'Client work', + color: '#eb6834', + ms: 2.75 * HOUR, + leaves: [{ label: 'Acme', isProject: true, ms: 2.75 * HOUR }] + }, + { + id: null, + name: 'Uncategorized', + color: '#8c8c8c', + ms: 1.5 * HOUR, + leaves: [ + { label: 'lost keys', isProject: false, ms: HOUR }, + { label: '(no title)', isProject: false, ms: 0.5 * HOUR } + ] + }, + { + id: 1, + name: 'Meetings', + color: '#2a78d6', + ms: HOUR, + leaves: [{ label: 'Standup', isProject: false, ms: HOUR }] + } + ]); + expect(report.entries.map((r) => r.category)).toEqual([ + 'Meetings', + 'Client work', + 'Client work', + 'Uncategorized', + 'Uncategorized' + ]); + }); + + it('lays out source → category → project links in hours', () => { + const { sankey } = buildReport(entries, categories, rules); + expect(sankey.nodes.map((n) => [n.id, n.label, n.depth])).toEqual([ + ['s:calendar', 'Calendar', 0], + ['s:timer', 'Timer', 0], + ['s:manual', 'Manual', 0], + ['s:import', 'Import', 0], + ['c:2', 'Client work', 1], + ['c:none', 'Uncategorized', 1], + ['c:1', 'Meetings', 1], + ['t:Standup', 'Standup', 2], + ['p:Acme', 'Acme', 2], + ['t:lost keys', 'lost keys', 2], + ['t:(no title)', '(no title)', 2] + ]); + expect(sankey.links).toEqual([ + { source: 's:calendar', target: 'c:1', hours: 1 }, + { source: 'c:1', target: 't:Standup', hours: 1 }, + { source: 's:timer', target: 'c:2', hours: 2 }, + { source: 'c:2', target: 'p:Acme', hours: 2.75 }, + { source: 's:manual', target: 'c:2', hours: 0.75 }, + { source: 's:timer', target: 'c:none', hours: 1 }, + { source: 'c:none', target: 't:lost keys', hours: 1 }, + { source: 's:import', target: 'c:none', hours: 0.5 }, + { source: 'c:none', target: 't:(no title)', hours: 0.5 } + ]); + const into = (id: string) => + sankey.links.filter((l) => l.target === id).reduce((sum, l) => sum + l.hours, 0); + const out = (id: string) => + sankey.links.filter((l) => l.source === id).reduce((sum, l) => sum + l.hours, 0); + for (const id of ['c:1', 'c:2', 'c:none']) expect(into(id)).toBeCloseTo(out(id)); + }); + + it('leaves out calendar time that tracked time wins', () => { + const report = buildReport(entries, categories, rules, { trackedWins: true }); + expect(report.totalMs).toBe(4.75 * HOUR); + expect(report.sankey.links[0]).toEqual({ source: 's:calendar', target: 'c:1', hours: 0.5 }); + + const covered = buildReport( + [entry('calendar', '09:00', '10:00', 'Standup'), entry('timer', '08:00', '11:00', 'Build')], + categories, + rules, + { trackedWins: true } + ); + expect(covered.entries[0].countedMs).toBe(0); + expect(covered.sankey.nodes.map((n) => n.id)).toEqual(['s:timer', 'c:none', 't:Build']); + expect(covered.totals.map((t) => t.name)).toEqual(['Uncategorized']); + }); + + it('keeps node ids unique when a project, title and category share a name', () => { + const { sankey } = buildReport( + [ + entry('timer', '09:00', '10:00', 'Calendar', 'Meetings'), + entry('manual', '10:00', '11:00', 'Meetings'), + entry('calendar', '11:00', '12:00', 'Meetings', 'Calendar') + ], + [{ id: 1, name: 'Calendar', color: '#2a78d6' }], + [rule(1, 'title', 'meetings')] + ); + const ids = sankey.nodes.map((n) => n.id); + expect(new Set(ids).size).toBe(ids.length); + expect(sankey.nodes.filter((n) => n.label === 'Meetings').map((n) => n.id)).toEqual([ + 'p:Meetings', + 't:Meetings' + ]); + for (const link of sankey.links) { + const depth = (id: string) => sankey.nodes.find((n) => n.id === id)!.depth; + expect(depth(link.target)).toBe(depth(link.source) + 1); + } + }); + + it('leaves links that round to 0 h out of the Sankey but counts them in the totals', () => { + const blip = { + ...entry('timer', '14:00', '14:00', 'Switched'), + end_at: '2026-11-02T14:00:05.000Z' + }; + const report = buildReport([entry('timer', '09:00', '10:00', 'Build'), blip], categories, []); + expect(report.totalMs).toBe(HOUR + 5000); + expect(report.sankey.nodes.map((n) => n.id)).toEqual(['s:timer', 'c:none', 't:Build']); + expect(report.sankey.links.map((l) => l.target)).toEqual(['c:none', 't:Build']); + expect(buildReport([blip], categories, []).sankey).toEqual({ nodes: [], links: [] }); + }); + + it('is empty without entries', () => { + expect(buildReport([], categories, rules)).toEqual({ + entries: [], + totals: [], + totalMs: 0, + overlapMs: 0, + sankey: { nodes: [], links: [] } + }); + }); +}); + +describe('toHours and sankeyHeight', () => { + it('rounds hours to hundredths', () => { + expect(toHours(HOUR * 1.5)).toBe(1.5); + expect(toHours(20 * 60_000)).toBe(0.33); + }); + + it('grows with the busiest column', () => { + expect(sankeyHeight([])).toBe(240); + const leaves = Array.from({ length: 20 }, (_, i) => ({ + id: `t:${i}`, + label: String(i), + color: '#000', + depth: 2 as const + })); + expect(sankeyHeight(leaves)).toBe(20 * 28 + 40); + }); +}); diff --git a/src/lib/report.ts b/src/lib/report.ts new file mode 100644 index 0000000..c33b68c --- /dev/null +++ b/src/lib/report.ts @@ -0,0 +1,324 @@ +/** + * Pure building blocks of the monthly time audit: categorizing entries by rules, resolving + * overlaps between calendar blocks and tracked time, and the Sankey and totals it shows. + */ + +export type Source = 'calendar' | 'timer' | 'manual' | 'import'; +export type RuleField = 'source' | 'project' | 'title'; +export type RuleMode = 'keyword' | 'regex'; + +export const SOURCE_LABELS: Record = { + calendar: 'Calendar', + timer: 'Timer', + manual: 'Manual', + import: 'Import' +}; + +export interface Category { + id: number; + name: string; + color: string; +} + +export interface CategoryRule { + id: number; + category_id: number; + field: RuleField; + mode: RuleMode; + pattern: string; +} + +/** A finished time entry, as stored. */ +export interface ReportEntry { + id: number; + source: Source; + start_at: string; + end_at: string; + title: string; + project: string | null; +} + +export const UNCATEGORIZED = { name: 'Uncategorized', color: '#8c8c8c' } as const; + +/** Default colors offered for new categories, in order (a colorblind-checked categorical set). */ +export const CATEGORY_COLORS = [ + '#2a78d6', + '#eb6834', + '#1baf7a', + '#eda100', + '#e87ba4', + '#008300', + '#6250d6', + '#e34948' +]; + +/** Why a rule cannot be saved, or null if it is fine. */ +export function ruleError(field: RuleField, mode: RuleMode, pattern: string): string | null { + if (!pattern.trim()) return 'Enter a pattern'; + if (field === 'source') { + return pattern in SOURCE_LABELS + ? null + : `Choose one of: ${Object.keys(SOURCE_LABELS).join(', ')}`; + } + if (mode === 'regex') { + try { + new RegExp(pattern, 'iu'); + } catch { + return 'Enter a valid regular expression'; + } + } + return null; +} + +type Matcher = (entry: Pick) => boolean; + +function compileRule(rule: CategoryRule): Matcher { + if (rule.field === 'source') return (e) => e.source === rule.pattern; + const value = (e: Parameters[0]) => + rule.field === 'project' ? (e.project ?? '') : e.title; + if (rule.mode === 'regex') { + let regex: RegExp; + try { + regex = new RegExp(rule.pattern, 'iu'); + } catch { + return () => false; + } + return (e) => regex.test(value(e)); + } + const keyword = rule.pattern.trim().toLowerCase(); + return (e) => value(e).toLowerCase().includes(keyword); +} + +/** + * A function giving the category id of an entry: that of the first rule (in the given order) + * that matches it, or null (Uncategorized). Invalid regular expressions never match. + */ +export function categorizer( + rules: CategoryRule[] +): (entry: Pick) => number | null { + const compiled = rules.map((rule) => ({ id: rule.category_id, matches: compileRule(rule) })); + return (entry) => compiled.find((r) => r.matches(entry))?.id ?? null; +} + +/** Time tracked by hand (timer, manual or import), as opposed to planned calendar blocks. */ +export function isTracked(source: Source): boolean { + return source !== 'calendar'; +} + +type Interval = [start: number, end: number]; + +/** Sorted, non-overlapping union of intervals. */ +function union(intervals: Interval[]): Interval[] { + const sorted = intervals.filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0]); + const merged: Interval[] = []; + for (const [s, e] of sorted) { + const last = merged.at(-1); + if (last && s <= last[1]) last[1] = Math.max(last[1], e); + else merged.push([s, e]); + } + return merged; +} + +/** How much of `[start, end)` the sorted, disjoint `cover` overlaps, in ms. */ +function coveredMs(start: number, end: number, cover: Interval[]): number { + let ms = 0; + for (const [s, e] of cover) { + if (s >= end) break; + ms += Math.max(0, Math.min(e, end) - Math.max(s, start)); + } + return ms; +} + +export interface Resolved { + entry: T; + /** The entry's full length in ms. */ + durationMs: number; + /** The ms counted in the report: less than the duration when tracked time won over it. */ + countedMs: number; + /** Ms of this calendar entry that tracked time also covers (0 for tracked entries). */ + overlapMs: number; +} + +/** + * Durations of entries, with the calendar time also covered by tracked time measured. With + * `trackedWins`, that overlap is not counted for the calendar entry, so the tracked entry is + * the only one to count it; otherwise both count it. + */ +export function resolveOverlaps>( + entries: T[], + trackedWins: boolean +): { entries: Resolved[]; overlapMs: number } { + const span = (e: T): Interval => [Date.parse(e.start_at), Date.parse(e.end_at)]; + const tracked = union(entries.filter((e) => isTracked(e.source)).map(span)); + let total = 0; + const resolved = entries.map((entry) => { + const [start, end] = span(entry); + const durationMs = Math.max(0, end - start); + const overlapMs = isTracked(entry.source) ? 0 : coveredMs(start, end, tracked); + total += overlapMs; + return { entry, durationMs, overlapMs, countedMs: durationMs - (trackedWins ? overlapMs : 0) }; + }); + return { entries: resolved, overlapMs: total }; +} + +export interface SankeyNode { + /** Unique across layers, e.g. `c:3`; ECharts uses it as the node name. */ + id: string; + label: string; + color: string; + /** 0 = source, 1 = category, 2 = project or title. */ + depth: 0 | 1 | 2; +} + +export interface SankeyLink { + source: string; + target: string; + hours: number; +} + +export interface LeafTotal { + label: string; + /** True when the leaf is a project, false when it is an entry title (no project). */ + isProject: boolean; + ms: number; +} + +export interface CategoryTotal { + /** Null for Uncategorized. */ + id: number | null; + name: string; + color: string; + ms: number; + leaves: LeafTotal[]; +} + +export interface Report { + entries: (Resolved & { categoryId: number | null; category: string })[]; + totals: CategoryTotal[]; + totalMs: number; + overlapMs: number; + sankey: { nodes: SankeyNode[]; links: SankeyLink[] }; +} + +const SOURCE_COLOR = '#8c8c8c'; +export const NO_TITLE = '(no title)'; + +/** Hours, rounded to hundredths. */ +export function toHours(ms: number): number { + return Math.round(ms / 36_000) / 100; +} + +function add(map: Map, key: K, ms: number) { + map.set(key, (map.get(key) ?? 0) + ms); +} + +const byMsDesc = (a: { ms: number }, b: { ms: number }) => b.ms - a.ms; + +/** + * Categorize and total a month of finished entries, and lay them out as a Sankey of + * source → category → project (or title when an entry has no project). Sums are kept in ms + * and only rounded to hours on the links, so the links and totals agree. + */ +export function buildReport( + entries: T[], + categories: Category[], + rules: CategoryRule[], + { trackedWins = false } = {} +): Report { + const categoryOf = categorizer(rules); + const byId = new Map(categories.map((c) => [c.id, c])); + const resolved = resolveOverlaps(entries, trackedWins); + const rows = resolved.entries.map((r) => { + const category = byId.get(categoryOf(r.entry) ?? -1); + return { + ...r, + categoryId: category?.id ?? null, + category: category?.name ?? UNCATEGORIZED.name + }; + }); + + const sourceMs = new Map(); + /** ms per `[source node, target node]` link, JSON-encoded. */ + const links = new Map(); + const totals = new Map }>(); + const leafNodes = new Map(); + + for (const row of rows) { + if (row.countedMs <= 0) continue; + const ms = row.countedMs; + const category = row.categoryId === null ? null : byId.get(row.categoryId)!; + const categoryKey = `c:${row.categoryId ?? 'none'}`; + const { project, title } = row.entry; + const isProject = project !== null && project !== ''; + const label = isProject ? project : title || NO_TITLE; + const leafKey = `${isProject ? 'p' : 't'}:${label}`; + + add(sourceMs, row.entry.source, ms); + add(links, JSON.stringify([`s:${row.entry.source}`, categoryKey]), ms); + add(links, JSON.stringify([categoryKey, leafKey]), ms); + if (!leafNodes.has(leafKey)) { + leafNodes.set(leafKey, { id: leafKey, label, color: SOURCE_COLOR, depth: 2 }); + } + + let total = totals.get(row.categoryId); + if (!total) { + total = { + id: row.categoryId, + name: category?.name ?? UNCATEGORIZED.name, + color: category?.color ?? UNCATEGORIZED.color, + ms: 0, + leaves: [], + leafMap: new Map() + }; + totals.set(row.categoryId, total); + } + total.ms += ms; + const leaf = total.leafMap.get(leafKey) ?? { label, isProject, ms: 0 }; + leaf.ms += ms; + total.leafMap.set(leafKey, leaf); + } + + const categoryTotals = [...totals.values()] + .map(({ leafMap, ...t }) => ({ ...t, leaves: [...leafMap.values()].sort(byMsDesc) })) + .sort(byMsDesc); + + const nodes: SankeyNode[] = [ + ...[...sourceMs.keys()].map((source) => ({ + id: `s:${source}`, + label: SOURCE_LABELS[source as Source], + color: SOURCE_COLOR, + depth: 0 as const + })), + ...categoryTotals.map((t) => ({ + id: `c:${t.id ?? 'none'}`, + label: t.name, + color: t.color, + depth: 1 as const + })), + ...leafNodes.values() + ]; + // Links that round to 0 h (a few seconds) would break the Sankey layout, so they are left + // out of the chart, with any node they leave unlinked; the totals still count them. + const sankeyLinks = [...links] + .map(([key, ms]) => { + const [source, target] = JSON.parse(key) as [string, string]; + return { source, target, hours: toHours(ms) }; + }) + .filter((link) => link.hours > 0); + const linked = new Set(sankeyLinks.flatMap((l) => [l.source, l.target])); + + return { + entries: rows, + totals: categoryTotals, + totalMs: categoryTotals.reduce((sum, t) => sum + t.ms, 0), + overlapMs: resolved.overlapMs, + sankey: { nodes: nodes.filter((n) => linked.has(n.id)), links: sankeyLinks } + }; +} + +/** A height that leaves each node of the busiest column room for its label. */ +export function sankeyHeight(nodes: SankeyNode[]): number { + const perColumn = [0, 0, 0]; + for (const node of nodes) perColumn[node.depth]++; + return Math.max(240, Math.max(...perColumn) * 28 + 40); +} diff --git a/src/lib/sankeyChart.spec.ts b/src/lib/sankeyChart.spec.ts new file mode 100644 index 0000000..252520b --- /dev/null +++ b/src/lib/sankeyChart.spec.ts @@ -0,0 +1,80 @@ +import * as echarts from 'echarts/core'; +import { describe, expect, it } from 'vitest'; +import { buildReport, type ReportEntry } from './report'; +import { sankeyOption } from './sankeyChart'; + +const entries: ReportEntry[] = [ + { + id: 1, + source: 'calendar', + start_at: '2026-11-02T09:00:00.000Z', + end_at: '2026-11-02T10:30:00.000Z', + title: 'Standup', + project: null + }, + { + id: 2, + source: 'timer', + start_at: '2026-11-02T11:00:00.000Z', + end_at: '2026-11-02T13:00:00.000Z', + title: 'Build it', + project: 'Meetings' + } +]; + +function render(list: ReportEntry[]): string { + const { sankey } = buildReport( + list, + [{ id: 1, name: 'Meetings', color: '#2a78d6' }], + [{ id: 1, category_id: 1, field: 'source', mode: 'keyword', pattern: 'calendar' }] + ); + const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 800, height: 300 }); + chart.setOption(sankeyOption(sankey.nodes, sankey.links, { text: '#111', muted: '#666' })); + const svg = chart.renderToSVGString(); + chart.dispose(); + return svg; +} + +/** Texts of the SVG's text elements. */ +const texts = (svg: string) => [...svg.matchAll(/]*>([^<]*)<\/text>/g)].map((m) => m[1]); + +const blip: ReportEntry = { + id: 3, + source: 'timer', + start_at: '2026-11-02T14:00:00.000Z', + end_at: '2026-11-02T14:00:05.000Z', + title: 'Switched', + project: null +}; + +describe('sankeyOption', () => { + it('renders with ECharts, showing labels and hours rather than node ids', () => { + const { sankey } = buildReport( + entries, + [{ id: 1, name: 'Meetings', color: '#2a78d6' }], + [{ id: 1, category_id: 1, field: 'source', mode: 'keyword', pattern: 'calendar' }] + ); + const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 800, height: 300 }); + chart.setOption(sankeyOption(sankey.nodes, sankey.links, { text: '#111', muted: '#666' })); + const svg = chart.renderToSVGString(); + chart.dispose(); + + expect(svg).toContain(''); + expect(texts(svg)).toEqual(expect.arrayContaining(['1.5 h', '2 h'])); + }); + + it('renders links of a few seconds, which round to 0 h', () => { + for (const list of [[blip], [...entries, blip]]) { + const svg = render(list); + expect(svg).toContain(' MAX_LABEL ? `${label.slice(0, MAX_LABEL - 1)}…` : label; +} + +const hours = (value: unknown) => + `${Number(value) + .toFixed(2) + .replace(/\.?0+$/, '')} h`; + +/** + * The ECharts option for a source → category → project Sankey. Nodes are keyed by their + * unique `id` and shown by `label`, so a project may share a category's name. + */ +export function sankeyOption( + nodes: SankeyNode[], + links: SankeyLink[], + colors: SankeyColors +): echarts.EChartsCoreOption { + const labels = new Map(nodes.map((n) => [n.id, n.label])); + const label = (id: unknown) => labels.get(String(id)) ?? String(id); + return { + animation: false, + tooltip: { + trigger: 'item', + formatter: (params: unknown) => { + const p = params as { dataType?: string; name: string; value: number; data: SankeyLink }; + const text = + p.dataType === 'edge' + ? `${label(p.data.source)} → ${label(p.data.target)}: ${hours(p.value)}` + : `${label(p.name)}: ${hours(p.value)}`; + return echarts.format.encodeHTML(text); + } + }, + series: [ + { + type: 'sankey', + left: 8, + right: 200, + top: 8, + bottom: 8, + nodeGap: 10, + draggable: false, + emphasis: { focus: 'adjacency' }, + data: nodes.map((n) => ({ name: n.id, depth: n.depth, itemStyle: { color: n.color } })), + links: links.map((l) => ({ source: l.source, target: l.target, value: l.hours })), + lineStyle: { color: 'gradient', opacity: 0.35, curveness: 0.5 }, + label: { + color: colors.text, + formatter: (p: { name: string; value: unknown }) => + `${shorten(label(p.name))} ${hours(p.value)}` + }, + edgeLabel: { + show: true, + color: colors.muted, + fontSize: 10, + formatter: (p: { value: unknown }) => hours(p.value) + } + } + ] + }; +} + +/** Draw the Sankey into `el`; returns a function that removes it. */ +export function renderSankey( + el: HTMLElement, + nodes: SankeyNode[], + links: SankeyLink[], + colors: SankeyColors +): () => void { + const chart = echarts.init(el, null, { renderer: 'svg' }); + chart.setOption(sankeyOption(nodes, links, colors)); + const observer = new ResizeObserver(() => chart.resize()); + observer.observe(el); + return () => { + observer.disconnect(); + chart.dispose(); + }; +} diff --git a/src/lib/server/audit.ts b/src/lib/server/audit.ts new file mode 100644 index 0000000..3f9acfe --- /dev/null +++ b/src/lib/server/audit.ts @@ -0,0 +1,60 @@ +import type Database from 'better-sqlite3'; +import { buildReport, NO_TITLE, SOURCE_LABELS, toHours, type Report } from '../report'; +import { listCategories, listRules } from './categories'; +import { currentMonth, isMonth, listMonthEntries, type TimeEntry } from './timeEntries'; +import { toLocalInput } from './zone'; + +export type MonthReport = Report; + +/** + * The time audit of `month` on the wall clock of `zone`: its finished entries (a running timer + * is left out until it stops), categorized by the current rules. + */ +export function monthReport( + db: Database.Database, + month: string, + zone: string, + { trackedWins = false } = {} +): MonthReport { + const entries = listMonthEntries(db, month, zone).filter( + (e): e is TimeEntry & { end_at: string } => e.end_at !== null + ); + return buildReport(entries, listCategories(db), listRules(db), { trackedWins }); +} + +export const REPORT_CSV_HEADER = [ + 'Start', + 'End', + 'Hours', + 'Counted hours', + 'Source', + 'Category', + 'Project', + 'Title' +]; + +/** One row per entry, times on the wall clock of `zone`. */ +export function reportCsvRows(report: MonthReport, zone: string): (string | number)[][] { + return [ + REPORT_CSV_HEADER, + ...report.entries.map(({ entry, durationMs, countedMs, category }) => [ + toLocalInput(entry.start_at, zone), + toLocalInput(entry.end_at, zone), + toHours(durationMs), + toHours(countedMs), + SOURCE_LABELS[entry.source], + category, + entry.project ?? '', + entry.title || NO_TITLE + ]) + ]; +} + +/** The month (default: the current one) and overlap option from a report URL. */ +export function reportParams(url: URL, zone: string): { month: string; trackedWins: boolean } { + const requested = url.searchParams.get('month') ?? ''; + return { + month: isMonth(requested) ? requested : currentMonth(zone), + trackedWins: url.searchParams.get('tracked') === 'wins' + }; +} diff --git a/src/lib/server/categories.spec.ts b/src/lib/server/categories.spec.ts new file mode 100644 index 0000000..9a609a1 --- /dev/null +++ b/src/lib/server/categories.spec.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from 'vitest'; +import { + addRule, + createCategory, + deleteCategory, + deleteRule, + listCategories, + listRules, + moveRule, + nextCategoryColor, + ruleSchema, + updateCategory +} from './categories'; +import { CATEGORY_COLORS } from '../report'; +import { createTestDb } from './testing/db'; + +describe('categories', () => { + it('creates, renames, recolors and deletes categories with unique names', () => { + const db = createTestDb(); + expect(nextCategoryColor(db)).toBe(CATEGORY_COLORS[0]); + const work = createCategory(db, { name: 'Work', color: CATEGORY_COLORS[0] }); + expect(work).toEqual({ id: 1, name: 'Work', color: CATEGORY_COLORS[0] }); + expect(nextCategoryColor(db)).toBe(CATEGORY_COLORS[1]); + expect(createCategory(db, { name: 'Work', color: '#000000' })).toEqual({ + error: 'There is already a category "Work"' + }); + createCategory(db, { name: 'admin', color: '#000000' }); + expect(updateCategory(db, 1, { name: 'admin', color: '#000000' })).toMatchObject({ + error: expect.any(String) as string + }); + expect(updateCategory(db, 1, { name: 'Client work', color: '#123456' })).toBe(true); + expect(updateCategory(db, 42, { name: 'x', color: '#123456' })).toBe(false); + expect(listCategories(db).map((c) => [c.name, c.color])).toEqual([ + ['admin', '#000000'], + ['Client work', '#123456'] + ]); + expect(deleteCategory(db, 1)).toBe(true); + expect(deleteCategory(db, 1)).toBe(false); + }); + + it('keeps rules in order, appends new ones and moves them', () => { + const db = createTestDb(); + const { id } = createCategory(db, { name: 'Work', color: '#000000' }) as { id: number }; + const a = addRule(db, { category_id: id, field: 'title', mode: 'keyword', pattern: 'a' })!; + const b = addRule(db, { category_id: id, field: 'source', mode: 'keyword', pattern: 'timer' })!; + const c = addRule(db, { category_id: id, field: 'project', mode: 'regex', pattern: '^c' })!; + expect(addRule(db, { category_id: 99, field: 'title', mode: 'keyword', pattern: 'x' })).toBe( + null + ); + const order = () => listRules(db).map((r) => r.id); + expect(order()).toEqual([a.id, b.id, c.id]); + + expect(moveRule(db, c.id, -1)).toBe(true); + expect(order()).toEqual([a.id, c.id, b.id]); + expect(moveRule(db, a.id, -1)).toBe(true); + expect(order()).toEqual([a.id, c.id, b.id]); + expect(moveRule(db, a.id, 1)).toBe(true); + expect(order()).toEqual([c.id, a.id, b.id]); + expect(moveRule(db, 99, 1)).toBe(false); + + expect(deleteRule(db, a.id)).toBe(true); + expect(deleteRule(db, a.id)).toBe(false); + const d = addRule(db, { category_id: id, field: 'title', mode: 'keyword', pattern: 'd' })!; + expect(order()).toEqual([c.id, b.id, d.id]); + + deleteCategory(db, id); + expect(listRules(db)).toEqual([]); + }); + + it('validates rule forms', () => { + const parse = (form: Record) => ruleSchema.safeParse(form); + expect( + parse({ category_id: '1', field: 'title', mode: 'regex', pattern: ' ^stand ' }).data + ).toEqual({ category_id: 1, field: 'title', mode: 'regex', pattern: '^stand' }); + expect( + parse({ category_id: '1', field: 'source', mode: 'regex', pattern: 'timer' }).data + ).toMatchObject({ mode: 'keyword' }); + const error = (form: Record) => parse(form).error?.issues[0].message; + expect(error({ category_id: '1', field: 'title', mode: 'regex', pattern: '[' })).toBe( + 'Enter a valid regular expression' + ); + expect(error({ category_id: '1', field: 'source', pattern: 'email' })).toMatch(/Choose one/); + expect(error({ category_id: '', field: 'title', pattern: 'x' })).toBe('Choose a category'); + expect(error({ category_id: '1', field: 'tags', pattern: 'x' })).toBeDefined(); + }); +}); diff --git a/src/lib/server/categories.ts b/src/lib/server/categories.ts new file mode 100644 index 0000000..fa0b0d8 --- /dev/null +++ b/src/lib/server/categories.ts @@ -0,0 +1,133 @@ +import type Database from 'better-sqlite3'; +import { z } from 'zod'; +import { + CATEGORY_COLORS, + ruleError, + type Category, + type CategoryRule, + type RuleField, + type RuleMode +} from '../report'; + +export function listCategories(db: Database.Database): Category[] { + return ( + db.prepare('SELECT id, name, color FROM categories ORDER BY name COLLATE NOCASE').all() as { + id: number; + name: string; + color: string | null; + }[] + ).map((c) => ({ ...c, color: c.color ?? CATEGORY_COLORS[(c.id - 1) % CATEGORY_COLORS.length] })); +} + +/** The default color for the next category: the first palette color not in use yet. */ +export function nextCategoryColor(db: Database.Database): string { + const used = new Set(listCategories(db).map((c) => c.color.toLowerCase())); + return ( + CATEGORY_COLORS.find((c) => !used.has(c)) ?? CATEGORY_COLORS[used.size % CATEGORY_COLORS.length] + ); +} + +/** Rules in the order they are tried. */ +export function listRules(db: Database.Database): CategoryRule[] { + return db + .prepare( + `SELECT id, category_id, field, mode, pattern FROM category_rules ORDER BY priority, id` + ) + .all() as CategoryRule[]; +} + +export const categorySchema = z.object({ + name: z.string().trim().min(1, 'Enter a name').max(100, 'Keep the name under 100 characters'), + color: z + .string() + .regex(/^#[0-9a-f]{6}$/i, 'Choose a color') + .transform((c) => c.toLowerCase()) +}); + +export type CategoryInput = z.infer; + +/** Create a category; returns an error message if the name is taken. */ +export function createCategory( + db: Database.Database, + input: CategoryInput +): Category | { error: string } { + const row = db + .prepare( + `INSERT INTO categories (name, color) VALUES (@name, @color) + ON CONFLICT (name) DO NOTHING RETURNING id, name, color` + ) + .get(input) as Category | undefined; + return row ?? { error: `There is already a category "${input.name}"` }; +} + +/** Rename or recolor a category; false if it does not exist, an error if the name is taken. */ +export function updateCategory( + db: Database.Database, + id: number, + input: CategoryInput +): boolean | { error: string } { + const taken = db + .prepare('SELECT 1 FROM categories WHERE name = ? AND id <> ?') + .get(input.name, id); + if (taken) return { error: `There is already a category "${input.name}"` }; + return ( + db + .prepare('UPDATE categories SET name = @name, color = @color WHERE id = @id') + .run({ ...input, id }).changes > 0 + ); +} + +/** Delete a category and its rules; its entries become Uncategorized. */ +export function deleteCategory(db: Database.Database, id: number): boolean { + return db.prepare('DELETE FROM categories WHERE id = ?').run(id).changes > 0; +} + +export const ruleSchema = z + .object({ + category_id: z.coerce.number().int().positive('Choose a category'), + field: z.enum(['source', 'project', 'title'] satisfies RuleField[]), + mode: z.enum(['keyword', 'regex'] satisfies RuleMode[]).default('keyword'), + pattern: z.string().trim().max(500, 'Keep the pattern under 500 characters') + }) + .superRefine((rule, ctx) => { + const error = ruleError(rule.field, rule.mode, rule.pattern); + if (error) ctx.addIssue({ code: 'custom', message: error, path: ['pattern'] }); + }) + .transform((rule) => (rule.field === 'source' ? { ...rule, mode: 'keyword' as const } : rule)); + +export type RuleInput = z.infer; + +/** Add a rule after every existing one; returns null if the category does not exist. */ +export function addRule(db: Database.Database, input: RuleInput): CategoryRule | null { + if (!db.prepare('SELECT 1 FROM categories WHERE id = ?').get(input.category_id)) return null; + return db + .prepare( + `INSERT INTO category_rules (category_id, field, mode, pattern, priority) + VALUES (@category_id, @field, @mode, @pattern, + (SELECT COALESCE(MAX(priority), 0) + 1 FROM category_rules)) + RETURNING id, category_id, field, mode, pattern` + ) + .get(input) as CategoryRule; +} + +export function deleteRule(db: Database.Database, id: number): boolean { + return db.prepare('DELETE FROM category_rules WHERE id = ?').run(id).changes > 0; +} + +/** + * Move a rule one place earlier (`-1`) or later (`1`) in the order. Returns false if there is + * no such rule; moving past either end leaves the order unchanged. + */ +export function moveRule(db: Database.Database, id: number, by: -1 | 1): boolean { + return db.transaction(() => { + const ids = listRules(db).map((r) => r.id); + const from = ids.indexOf(id); + if (from < 0) return false; + const to = from + by; + if (to < 0 || to >= ids.length) return true; + [ids[from], ids[to]] = [ids[to], ids[from]]; + const set = db.prepare('UPDATE category_rules SET priority = ? WHERE id = ?'); + ids.forEach((ruleId, i) => set.run(i + 1, ruleId)); + return true; + })(); +} diff --git a/src/lib/server/csv.spec.ts b/src/lib/server/csv.spec.ts new file mode 100644 index 0000000..1585a6a --- /dev/null +++ b/src/lib/server/csv.spec.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from 'vitest'; +import { parseCsv, toCsv } from './csv'; + +describe('toCsv', () => { + it('quotes what needs quoting and reads back with parseCsv', () => { + const rows = [ + ['Title', 'Hours'], + ['Email, invoices and "misc"', 1.5], + ['two\nlines', 0], + ['plain', 12] + ]; + const text = toCsv(rows); + expect(text).toBe( + 'Title,Hours\r\n"Email, invoices and ""misc""",1.5\r\n"two\nlines",0\r\nplain,12\r\n' + ); + expect(parseCsv(text).map((r) => r.fields)).toEqual(rows.map((r) => r.map(String))); + }); + + it('defuses text a spreadsheet would run as a formula', () => { + expect(toCsv([['=HYPERLINK("x")', '+1', '-a', '@b', 'ok', -2]])).toBe( + `"'=HYPERLINK(""x"")",'+1,'-a,'@b,ok,-2\r\n` + ); + }); +}); diff --git a/src/lib/server/csv.ts b/src/lib/server/csv.ts index 3c0b1be..9c5c6fc 100644 --- a/src/lib/server/csv.ts +++ b/src/lib/server/csv.ts @@ -74,3 +74,19 @@ export function parseCsv(text: string, delimiter = detectDelimiter(text)): CsvRe if (field !== '' || fields.length > 0) endRecord(); return records; } + +/** Cells a spreadsheet would run as a formula (CSV injection), unless prefixed with `'`. */ +const FORMULA_START = /^[=+\-@\t\r]/; + +/** + * Write RFC 4180 CSV with CRLF line endings. Text cells that a spreadsheet would read as a + * formula get a leading `'`; numbers are written as they are. + */ +export function toCsv(rows: (string | number)[][]): string { + const cell = (value: string | number) => { + if (typeof value === 'number') return String(value); + const text = FORMULA_START.test(value) ? `'${value}` : value; + return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text; + }; + return rows.map((row) => row.map(cell).join(',') + '\r\n').join(''); +} diff --git a/src/lib/server/db/db.spec.ts b/src/lib/server/db/db.spec.ts index 9c90f01..a6f0047 100644 --- a/src/lib/server/db/db.spec.ts +++ b/src/lib/server/db/db.spec.ts @@ -140,6 +140,30 @@ describe('schema', () => { expect(db.prepare('SELECT COUNT(*) FROM time_entries').pluck().get()).toBe(0); }); + it('keeps category rules when rebuilding category_rules', () => { + const db = new Database(':memory:'); + db.pragma('foreign_keys = ON'); + migrate( + db, + bundledMigrations.filter((m) => m.version < 6) + ); + db.prepare("INSERT INTO categories (id, name) VALUES (1, 'Work')").run(); + db.prepare( + "INSERT INTO category_rules (category_id, field, pattern, priority) VALUES (1, 'project', 'acme', 2)" + ).run(); + expect(migrate(db)).toContain(6); + expect( + db.prepare('SELECT category_id, field, mode, pattern, priority FROM category_rules').all() + ).toEqual([ + { category_id: 1, field: 'project', mode: 'keyword', pattern: 'acme', priority: 2 } + ]); + db.prepare( + "INSERT INTO category_rules (category_id, field, pattern) VALUES (1, 'source', 'timer')" + ).run(); + db.prepare('DELETE FROM categories WHERE id = 1').run(); + expect(db.prepare('SELECT COUNT(*) FROM category_rules').pluck().get()).toBe(0); + }); + it('enforces foreign keys', () => { const db = createTestDb(); expect(() => diff --git a/src/lib/server/db/migrations/006_category_rules.sql b/src/lib/server/db/migrations/006_category_rules.sql new file mode 100644 index 0000000..677e18b --- /dev/null +++ b/src/lib/server/db/migrations/006_category_rules.sql @@ -0,0 +1,22 @@ +-- Rules can now also match an entry's source, and match a keyword or a regular expression. +-- SQLite cannot change a CHECK in place, so the table is rebuilt with the same rows. +CREATE TABLE category_rules_new ( + id INTEGER PRIMARY KEY, + category_id INTEGER NOT NULL REFERENCES categories (id) ON DELETE CASCADE, + field TEXT NOT NULL DEFAULT 'title' CHECK (field IN ('source', 'project', 'title')), + -- How `pattern` is matched: a case-insensitive substring or regular expression. Source rules + -- compare the source name exactly. + mode TEXT NOT NULL DEFAULT 'keyword' CHECK (mode IN ('keyword', 'regex')), + pattern TEXT NOT NULL, + -- Rules are tried in ascending priority, then id; the first match wins. + priority INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')) +); + +INSERT INTO category_rules_new (id, category_id, field, pattern, priority, created_at) +SELECT id, category_id, field, pattern, priority, created_at FROM category_rules; + +DROP TABLE category_rules; +ALTER TABLE category_rules_new RENAME TO category_rules; + +CREATE INDEX category_rules_order_idx ON category_rules (priority, id); diff --git a/src/routes/report/+page.server.ts b/src/routes/report/+page.server.ts new file mode 100644 index 0000000..740f791 --- /dev/null +++ b/src/routes/report/+page.server.ts @@ -0,0 +1,22 @@ +import { monthReport, reportParams } from '#lib/server/audit.ts'; +import { getDb } from '#lib/server/db/index.ts'; +import { shiftMonth } from '#lib/server/timeEntries.ts'; +import { serverZone } from '#lib/server/zone.ts'; +import type { PageServerLoad } from './$types'; + +export const load: PageServerLoad = ({ url }) => { + const zone = serverZone(); + const { month, trackedWins } = reportParams(url, zone); + const report = monthReport(getDb(), month, zone, { trackedWins }); + return { + month, + prevMonth: shiftMonth(month, -1), + nextMonth: shiftMonth(month, 1), + trackedWins, + entryCount: report.entries.length, + totals: report.totals, + totalMs: report.totalMs, + overlapMs: report.overlapMs, + sankey: report.sankey + }; +}; diff --git a/src/routes/report/+page.svelte b/src/routes/report/+page.svelte index 53aa1e9..25b9e45 100644 --- a/src/routes/report/+page.svelte +++ b/src/routes/report/+page.svelte @@ -1,6 +1,197 @@ - i.href === '/report')!} /> + + Report · dumpdown + + +

Report

+ +
+ ← +

{monthLabel}

+ → + + + + + Export CSV + +
+ +

+ {formatDuration(data.totalMs)} counted from {data.entryCount} entries. + {#if data.overlapMs > 0} + {formatDuration(data.overlapMs)} of calendar time overlaps timer, manual or imported time; + {data.trackedWins + ? 'it is counted once, for the tracked entry.' + : 'it is counted twice, once for each.'} + {/if} + A running timer counts once it stops. +

+ +{#if data.totals.length === 0} +

+ No finished time entries this month. Add some on Time. +

+{:else} +
+ +
+ +
+

Totals

+ + + + + + {#each data.totals as category (category.id)} + + + + + + {#each category.leaves as leaf (`${leaf.isProject}:${leaf.label}`)} + + + + + + {/each} + {/each} + + + + +
Category / projectHoursShare
+ + {category.name} + {hours(category.ms)}{share(category.ms)}
{leaf.label}{hours(leaf.ms)}{share(leaf.ms)}
Total{hours(data.totalMs)}
+

+ Entries without a project are listed by title, in italics. Categories come from the rules on + Settings. +

+
+{/if} + + diff --git a/src/routes/report/export/+server.ts b/src/routes/report/export/+server.ts new file mode 100644 index 0000000..97d47ed --- /dev/null +++ b/src/routes/report/export/+server.ts @@ -0,0 +1,18 @@ +import { monthReport, reportCsvRows, reportParams } from '#lib/server/audit.ts'; +import { toCsv } from '#lib/server/csv.ts'; +import { getDb } from '#lib/server/db/index.ts'; +import { serverZone } from '#lib/server/zone.ts'; +import type { RequestHandler } from './$types'; + +/** The month's entries with their category and counted hours, as a CSV download. */ +export const GET: RequestHandler = ({ url }) => { + const zone = serverZone(); + const { month, trackedWins } = reportParams(url, zone); + const report = monthReport(getDb(), month, zone, { trackedWins }); + return new Response(toCsv(reportCsvRows(report, zone)), { + headers: { + 'content-type': 'text/csv; charset=utf-8', + 'content-disposition': `attachment; filename="dumpdown-${month}.csv"` + } + }); +}; diff --git a/src/routes/report/page.server.spec.ts b/src/routes/report/page.server.spec.ts new file mode 100644 index 0000000..ab6c94e --- /dev/null +++ b/src/routes/report/page.server.spec.ts @@ -0,0 +1,111 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { tempDbPath } from '#lib/server/testing/db.ts'; +import { fixture } from '#lib/server/testing/fixtures.ts'; + +/** Run a form action with a POSTed form body. */ +function submit(action: (event: never) => unknown, body: Record | FormData = {}) { + const request = new Request('http://localhost/settings', { + method: 'POST', + body: body instanceof FormData ? body : new URLSearchParams(body) + }); + return action({ request } as never); +} + +interface ReportData { + month: string; + prevMonth: string; + trackedWins: boolean; + entryCount: number; + totalMs: number; + overlapMs: number; + totals: { name: string; ms: number; leaves: { label: string; ms: number }[] }[]; + sankey: { nodes: { id: string }[]; links: { source: string; target: string; hours: number }[] }; +} + +const HOUR = 3_600_000; + +describe('report page and CSV export', () => { + let cleanup = () => {}; + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllEnvs(); + cleanup(); + }); + + async function setup() { + const tmp = tempDbPath(); + cleanup = tmp.cleanup; + vi.stubEnv('DATABASE_PATH', tmp.path); + vi.stubEnv('TZ', 'UTC'); + vi.useFakeTimers({ now: new Date('2026-11-15T12:00:00Z'), toFake: ['Date'] }); + vi.resetModules(); + const report = await import('./+page.server'); + const exporter = await import('./export/+server'); + const settings = await import('../settings/+page.server'); + const time = await import('../time/+page.server'); + const load = (query = '') => + report.load({ + url: new URL(`http://localhost/report${query}`) + } as Parameters[0]) as ReportData; + const download = async (query = '') => { + const response = await exporter.GET({ + url: new URL(`http://localhost/report/export${query}`) + } as Parameters[0]); + return { response, text: await response.text() }; + }; + return { settings: settings.actions, time: time.actions, load, download }; + } + + it('reports a month by category, with overlaps and a CSV export', async () => { + const { settings, time, load, download } = await setup(); + const ics = new FormData(); + ics.set('file', new File([fixture('simple.ics')], 'cal.ics')); + await submit(time.upload, ics); + const calendar = load(); + expect(calendar.entryCount).toBeGreaterThan(0); + expect(calendar.totals.map((t) => t.name)).toEqual(['Uncategorized']); + + await submit(settings.addCategory, { name: 'Meetings', color: '#2a78d6' }); + await submit(settings.addCategory, { name: 'Build', color: '#eb6834' }); + await submit(settings.addRule, { category_id: '1', field: 'source', pattern: 'calendar' }); + await submit(settings.addRule, { category_id: '2', field: 'project', pattern: 'dumpdown' }); + + const [meeting] = (await import('#lib/server/timeEntries.ts')) + .listMonthEntries((await import('#lib/server/db/index.ts')).getDb(), '2026-11', 'UTC') + .filter((e) => e.source === 'calendar'); + const start = meeting.start_at.slice(0, 16); + const end = new Date(Date.parse(meeting.start_at) + 30 * 60_000).toISOString().slice(0, 16); + await submit(time.addEntry, { title: 'Report =1+1', project: 'dumpdown', start, end }); + // A running timer is left out until it stops. + await submit(time.startTimer, { title: 'Running', project: 'dumpdown' }); + + const both = load('?month=2026-11'); + expect(both.overlapMs).toBe(0.5 * HOUR); + expect(both.totals.find((t) => t.name === 'Build')).toMatchObject({ + ms: 0.5 * HOUR, + leaves: [{ label: 'dumpdown', ms: 0.5 * HOUR }] + }); + expect(both.sankey.links).toContainEqual({ source: 's:manual', target: 'c:2', hours: 0.5 }); + + const wins = load('?month=2026-11&tracked=wins'); + expect(wins.trackedWins).toBe(true); + expect(wins.totalMs).toBe(both.totalMs - 0.5 * HOUR); + + expect(load('?month=2026-02')).toMatchObject({ entryCount: 0, totals: [], totalMs: 0 }); + expect(load('?month=nope')).toMatchObject({ month: '2026-11', prevMonth: '2026-10' }); + + const { response, text } = await download('?month=2026-11&tracked=wins'); + expect(response.headers.get('content-type')).toBe('text/csv; charset=utf-8'); + expect(response.headers.get('content-disposition')).toBe( + 'attachment; filename="dumpdown-2026-11.csv"' + ); + const lines = text.trimEnd().split('\r\n'); + expect(lines[0]).toBe('Start,End,Hours,Counted hours,Source,Category,Project,Title'); + expect(lines).toContain(`${start},${end},0.5,0.5,Manual,Build,dumpdown,Report =1+1`); + expect(lines.some((l) => l.startsWith(`${start},`) && l.includes(',Calendar,Meetings,'))).toBe( + true + ); + expect(lines.length).toBe(wins.entryCount + 1); + expect(text).not.toContain('Running'); + }); +}); diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.ts index 42e0b9e..9ebd5ae 100644 --- a/src/routes/settings/+page.server.ts +++ b/src/routes/settings/+page.server.ts @@ -10,7 +10,21 @@ import { setIncludeAllDay, syncCalendar } from '#lib/server/calendars.ts'; +import { + addRule, + categorySchema, + createCategory, + deleteCategory, + deleteRule, + listCategories, + listRules, + moveRule, + nextCategoryColor, + ruleSchema, + updateCategory +} from '#lib/server/categories.ts'; import { getDb } from '#lib/server/db/index.ts'; +import { formText } from '#lib/server/timeEntries.ts'; import type { Actions, PageServerLoad } from './$types'; export const load: PageServerLoad = () => { @@ -22,7 +36,10 @@ export const load: PageServerLoad = () => { host: new URL(url).host })), includeAllDay: getIncludeAllDay(db), - syncMinutes: resolveSyncMinutes() + syncMinutes: resolveSyncMinutes(), + categories: listCategories(db), + rules: listRules(db), + nextColor: nextCategoryColor(db) }; }; @@ -69,5 +86,63 @@ export const actions = { const include = (await request.formData()).get('includeAllDay') === 'on'; setIncludeAllDay(getDb(), include); return { includeAllDay: include }; + }, + + addCategory: async ({ request }) => { + const form = await request.formData(); + const parsed = categorySchema.safeParse(Object.fromEntries(form)); + if (!parsed.success) return fail(400, { categoryError: parsed.error.issues[0].message }); + const created = createCategory(getDb(), parsed.data); + if ('error' in created) return fail(409, { categoryError: created.error }); + return { categoryAdded: created.id }; + }, + + updateCategory: async ({ request }) => { + const form = await request.formData(); + const id = readId(form); + const parsed = categorySchema.safeParse(Object.fromEntries(form)); + if (!parsed.success) return fail(400, { categoryError: parsed.error.issues[0].message }); + const updated = id ? updateCategory(getDb(), id, parsed.data) : false; + if (updated === false) return fail(404, { categoryError: 'Category not found' }); + if (updated !== true) return fail(409, { categoryError: updated.error }); + return { categoryUpdated: id }; + }, + + /** Its rules go with it; its entries become Uncategorized. */ + deleteCategory: async ({ request }) => { + const id = readId(await request.formData()); + if (!id || !deleteCategory(getDb(), id)) { + return fail(404, { categoryError: 'Category not found' }); + } + return { categoryDeleted: id }; + }, + + addRule: async ({ request }) => { + const form = await request.formData(); + const parsed = ruleSchema.safeParse(Object.fromEntries(form)); + if (!parsed.success) { + return fail(400, { + ruleError: parsed.error.issues[0].message, + pattern: formText(form, 'pattern') ?? '' + }); + } + const rule = addRule(getDb(), parsed.data); + if (!rule) return fail(404, { ruleError: 'Category not found' }); + return { ruleAdded: rule.id }; + }, + + deleteRule: async ({ request }) => { + const id = readId(await request.formData()); + if (!id || !deleteRule(getDb(), id)) return fail(404, { ruleError: 'Rule not found' }); + return { ruleDeleted: id }; + }, + + /** Move a rule one place up (`dir=up`) or down in the order. */ + moveRule: async ({ request }) => { + const form = await request.formData(); + const id = readId(form); + const by = form.get('dir') === 'up' ? -1 : 1; + if (!id || !moveRule(getDb(), id, by)) return fail(404, { ruleError: 'Rule not found' }); + return { ruleMoved: id }; } } satisfies Actions; diff --git a/src/routes/settings/+page.svelte b/src/routes/settings/+page.svelte index 3420da0..cbbdd15 100644 --- a/src/routes/settings/+page.svelte +++ b/src/routes/settings/+page.svelte @@ -1,5 +1,7 @@ @@ -138,6 +147,168 @@ +
+

Categories

+

+ The monthly report groups time entries into categories. Each + entry gets the category of the first rule below that matches it, or Uncategorized. +

+ {#if data.categories.length} +
    + {#each data.categories as category (category.id)} +
  • +
    + + + + + +
    +
  • + {/each} +
+ {/if} +
+

Add a category

+
+ + + +
+
+ {#if form && 'categoryError' in form && form.categoryError} + + {/if} + +

Rules

+ {#if data.rules.length === 0} +

No rules yet: every entry is Uncategorized.

+ {:else} +
    + {#each data.rules as rule, i (rule.id)} +
  1. +
    + + If {ruleText(rule)} → {categoryName(rule.category_id)} + +
    + + + + +
    +
    +
  2. + {/each} +
+ {/if} + {#if data.categories.length} +
+

Add a rule

+
+ + {#if ruleField === 'source'} + + {:else} + + + {/if} + + +
+

+ Matching ignores case. New rules go last; move them up to take precedence. +

+
+ {/if} + {#if form && 'ruleError' in form && form.ruleError} + + {/if} +
+