Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

analytics-data.ts

70 lines2.2 KB

1import { localDay } from "@/db/queries";
2import type { Folder } from "@/db/schema";
3​
4/*
5 * Turns the analytics live queries' rows (`folderStatsQuery`,
6 * `editsPerDayQuery` in `db/queries.ts`) into what the charts draw: folder
7 * names, days without edits, the chart's date range. The counting happens in
8 * the queries, incrementally.
9 */
10​
11export interface FolderChartRow {
12 folderId: string;
13 name: string;
14 notes: number;
15 words: number;
17​
18/** One row per folder, in sidebar order; folders without notes count zero. */
19export function folderChartRows(
20 folders: readonly Pick<Folder, "id" | "name">[],
21 stats: readonly { folderId: string; notes: number; words: number | null | undefined }[],
22): FolderChartRow[] {
23 const byFolder = new Map(stats.map((row) => [row.folderId, row]));
24 return folders.map((folder) => {
25 const row = byFolder.get(folder.id);
26 return {
27 folderId: folder.id,
28 name: folder.name,
29 notes: row?.notes ?? 0,
30 words: row?.words ?? 0,
31 };
32 });
34​
35export interface DayChartRow {
36 /** `YYYY-MM-DD`, local time. */
37 day: string;
38 /** Short label for the axis, e.g. "3 Nov". */
39 label: string;
40 notes: number;
42​
43/** How many days the chart shows, ending today. */
44export const RECENT_DAYS = 14;
45​
46const dayLabel = new Intl.DateTimeFormat("en-GB", { day: "numeric", month: "short" });
47​
48/**
49 * Notes by day of last edit, for the last `days` days (oldest first, days
50 * without edits at zero), and how many notes were last edited before that.
51 * `today` is a local `YYYY-MM-DD`.
52 */
53export function recentDayRows(
54 perDay: readonly { day: string; notes: number }[],
55 today: string,
56 days = RECENT_DAYS,
57): { rows: DayChartRow[]; earlier: number } {
58 const counts = new Map(perDay.map((row) => [row.day, row.notes]));
59 const end = new Date(`${today}T12:00`);
60 const rows: DayChartRow[] = [];
61 for (let offset = days - 1; offset >= 0; offset--) {
62 const date = new Date(end);
63 date.setDate(end.getDate() - offset);
64 const day = localDay(date.toISOString());
65 rows.push({ day, label: dayLabel.format(date), notes: counts.get(day) ?? 0 });
66 }
67 const first = rows[0]!.day;
68 const earlier = perDay.filter((row) => row.day < first).reduce((sum, row) => sum + row.notes, 0);
69 return { rows, earlier };