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('