Files
everythingbutwork/apps/api/src/routers/time.ts
T
Raffael SheikhandClaude Opus 4.8 7dd1f2fb20 Feature: Zeit-pro-Projekt-Auswertung im Projekt-Detail
time_entry erfasst bezugKind='project'+bezugId, aber niemand sah je, wie viel
Zeit ein Projekt frisst. Neue Query time.byProject (Gesamtsumme + pro Person);
neue "Getrackte Zeit"-Sektion im Projekt-Detail (blendet sich aus, wenn nichts
getrackt wurde).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 12:15:05 +02:00

458 lines
16 KiB
TypeScript

import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { and, eq, isNull, asc, desc, sql, inArray } from 'drizzle-orm';
import { timeEntry, dayEntry, todo, user, type TimeEntry, type Db } from '@cockpit/db';
import { TimeEntrySchemas } from '@cockpit/shared';
import { router, protectedProcedure } from '../trpc.js';
import { todayIso, berlinDayStartMs } from '../lib/werktag.js';
// Einträge, die „heute" betreffen: heute gestartet ODER heute beendet (über
// Mitternacht gelaufen) ODER aktuell laufend. Gemeinsam für listToday/teamToday.
function overlapsToday(today: string) {
return sql`(
(${timeEntry.startedAt} AT TIME ZONE 'Europe/Berlin')::date = ${today}
OR (${timeEntry.endedAt} AT TIME ZONE 'Europe/Berlin')::date = ${today}
OR ${timeEntry.endedAt} IS NULL
)`;
}
const idInput = z.object({ id: z.string().uuid() });
/**
* Wall-Clock-Sekunden: Vereinigung überlappender Zeitintervalle. Parallel
* laufende Einträge (mehrere Tasks gleichzeitig) zählen nur einmal — damit
* „Gesamt heute" die tatsächlich anwesende Zeit zeigt, nicht die Summe.
*/
function unionSeconds(intervals: Array<readonly [number, number]>): number {
const valid = intervals.filter(([s, e]) => e > s).sort((a, b) => a[0] - b[0]);
if (valid.length === 0) return 0;
let total = 0;
let curStart = valid[0]![0];
let curEnd = valid[0]![1];
for (let i = 1; i < valid.length; i++) {
const [s, e] = valid[i]!;
if (s <= curEnd) {
if (e > curEnd) curEnd = e;
} else {
total += curEnd - curStart;
curStart = s;
curEnd = e;
}
}
total += curEnd - curStart;
return Math.round(total / 1000);
}
async function stopOneEntry(db: Db, entry: TimeEntry, now: Date): Promise<TimeEntry | null> {
const durationSeconds = Math.max(
0,
Math.round((now.getTime() - entry.startedAt.getTime()) / 1000),
);
const [stopped] = await db
.update(timeEntry)
.set({ endedAt: now, durationSeconds, updatedAt: now })
.where(eq(timeEntry.id, entry.id))
.returning();
return stopped ?? null;
}
// Stoppt ALLE laufenden Timer eines Users (mehrere parallele möglich).
async function stopAllActive(db: Db, userId: string, now: Date): Promise<number> {
const actives = await db
.select()
.from(timeEntry)
.where(and(eq(timeEntry.userId, userId), isNull(timeEntry.endedAt)));
for (const a of actives) await stopOneEntry(db, a, now);
return actives.length;
}
async function findCurrentDayEntryId(db: Db, userId: string): Promise<string | null> {
const date = todayIso();
const row = (
await db
.select({ id: dayEntry.id })
.from(dayEntry)
.where(and(eq(dayEntry.userId, userId), eq(dayEntry.date, date)))
.limit(1)
)[0];
return row?.id ?? null;
}
export const timeRouter = router({
/**
* Alle laufenden Timer des eingeloggten Users (mehrere parallel möglich).
*/
now: protectedProcedure.query(async ({ ctx }) => {
const rows = await ctx.db
.select()
.from(timeEntry)
.where(and(eq(timeEntry.userId, ctx.user.id), isNull(timeEntry.endedAt)))
.orderBy(desc(timeEntry.startedAt));
const todoIds = Array.from(new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)));
const titles = new Map<string, string>();
if (todoIds.length > 0) {
const tr = await ctx.db
.select({ id: todo.id, title: todo.title })
.from(todo)
.where(inArray(todo.id, todoIds));
for (const t of tr) titles.set(t.id, t.title);
}
return rows.map((r) => ({ ...r, todoTitle: r.todoId ? (titles.get(r.todoId) ?? null) : null }));
}),
/**
* Startet einen neuen Timer — parallel zu evtl. bereits laufenden (ENTWICKLUN-6).
*/
start: protectedProcedure
.input(TimeEntrySchemas.startTimeEntryInput)
.mutation(async ({ ctx, input }) => {
const now = new Date();
const dayEntryId = await findCurrentDayEntryId(ctx.db, ctx.user.id);
const [created] = await ctx.db
.insert(timeEntry)
.values({
userId: ctx.user.id,
dayEntryId,
todoId: input.todoId ?? null,
category: input.category,
description: input.description ?? null,
startedAt: now,
})
.returning();
if (!created) throw new Error('Time-Entry konnte nicht angelegt werden.');
return created;
}),
/**
* Stoppt einen bestimmten laufenden Timer.
*/
stop: protectedProcedure.input(idInput).mutation(async ({ ctx, input }) => {
const existing = (
await ctx.db.select().from(timeEntry).where(eq(timeEntry.id, input.id)).limit(1)
)[0];
if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
if (existing.userId !== ctx.user.id) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Nicht dein Eintrag.' });
}
if (existing.endedAt) return existing;
return stopOneEntry(ctx.db, existing, new Date());
}),
/**
* Stoppt alle laufenden Timer des Users.
*/
stopAll: protectedProcedure.mutation(async ({ ctx }) => {
const stopped = await stopAllActive(ctx.db, ctx.user.id, new Date());
return { stopped };
}),
/**
* Alle Time-Entries des heutigen Tages plus aktiver.
*/
listToday: protectedProcedure.query(async ({ ctx }) => {
const today = todayIso();
const dayStart = berlinDayStartMs(today);
const now = Date.now();
const rows = await ctx.db
.select()
.from(timeEntry)
.where(and(eq(timeEntry.userId, ctx.user.id), overlapsToday(today)))
.orderBy(desc(timeEntry.startedAt));
// ToDo-Titel tagesübergreifend auflösen (ToDo kann von gestern sein).
const todoIds = Array.from(new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)));
const titles = new Map<string, string>();
if (todoIds.length > 0) {
const tr = await ctx.db
.select({ id: todo.id, title: todo.title })
.from(todo)
.where(inArray(todo.id, todoIds));
for (const t of tr) titles.set(t.id, t.title);
}
// Für die Tages-Summen nur den HEUTIGEN Anteil zählen (über Mitternacht
// gelaufene Blöcke nicht doppelt/falsch zuschlagen).
const clampStart = (r: TimeEntry) => Math.max(r.startedAt.getTime(), dayStart);
const endMs = (r: TimeEntry) => (r.endedAt ? r.endedAt.getTime() : now);
const totalSeconds = unionSeconds(rows.map((r) => [clampStart(r), endMs(r)] as const));
const trackedSeconds = rows.reduce(
(acc, r) => acc + Math.max(0, Math.round((endMs(r) - clampStart(r)) / 1000)),
0,
);
const entries = rows.map((r) => ({
...r,
todoTitle: r.todoId ? (titles.get(r.todoId) ?? null) : null,
}));
return { entries, totalSeconds, trackedSeconds };
}),
/**
* Eintrag korrigieren (Zeiten, ToDo, Kategorie, Beschreibung).
*/
update: protectedProcedure
.input(TimeEntrySchemas.updateTimeEntryInput)
.mutation(async ({ ctx, input }) => {
const existing = (
await ctx.db.select().from(timeEntry).where(eq(timeEntry.id, input.id)).limit(1)
)[0];
if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
if (existing.userId !== ctx.user.id) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Nicht dein Eintrag.' });
}
const startedAt = input.startedAt ? new Date(input.startedAt) : existing.startedAt;
const endedAt =
input.endedAt === undefined
? existing.endedAt
: input.endedAt === null
? null
: new Date(input.endedAt);
const durationSeconds = endedAt
? Math.max(0, Math.round((endedAt.getTime() - startedAt.getTime()) / 1000))
: null;
const [updated] = await ctx.db
.update(timeEntry)
.set({
startedAt,
endedAt,
durationSeconds,
todoId: input.todoId === undefined ? existing.todoId : input.todoId,
category: input.category ?? existing.category,
description: input.description === undefined ? existing.description : input.description,
updatedAt: new Date(),
})
.where(eq(timeEntry.id, input.id))
.returning();
return updated;
}),
/**
* Eintrag retroaktiv anlegen (Nachtragen).
*/
upsertManual: protectedProcedure
.input(TimeEntrySchemas.manualTimeEntryInput)
.mutation(async ({ ctx, input }) => {
const startedAt = new Date(input.startedAt);
const endedAt = new Date(input.endedAt);
if (endedAt <= startedAt) {
throw new TRPCError({
code: 'BAD_REQUEST',
message: 'Endzeit muss nach der Startzeit liegen.',
});
}
const dayEntryId = await findCurrentDayEntryId(ctx.db, ctx.user.id);
const durationSeconds = Math.round((endedAt.getTime() - startedAt.getTime()) / 1000);
const [created] = await ctx.db
.insert(timeEntry)
.values({
userId: ctx.user.id,
dayEntryId,
todoId: input.todoId ?? null,
category: input.category,
description: input.description ?? null,
startedAt,
endedAt,
durationSeconds,
})
.returning();
return created;
}),
delete: protectedProcedure.input(idInput).mutation(async ({ ctx, input }) => {
const existing = (
await ctx.db.select().from(timeEntry).where(eq(timeEntry.id, input.id)).limit(1)
)[0];
if (!existing) throw new TRPCError({ code: 'NOT_FOUND', message: 'Eintrag nicht gefunden.' });
if (existing.userId !== ctx.user.id) {
throw new TRPCError({ code: 'FORBIDDEN', message: 'Nicht dein Eintrag.' });
}
await ctx.db.delete(timeEntry).where(eq(timeEntry.id, input.id));
return { ok: true };
}),
/**
* Team-Sicht: was hat das Team heute getrackt + wer arbeitet gerade an was.
* Heutige Zeit-Daten sind teamweit sichtbar.
*/
teamToday: protectedProcedure.query(async ({ ctx }) => {
const today = todayIso();
const dayStart = berlinDayStartMs(today);
const rows = await ctx.db
.select()
.from(timeEntry)
// Heute betroffen: heute gestartet/beendet oder laufend (auch über Mitternacht).
.where(overlapsToday(today));
const todoIds = Array.from(
new Set(rows.map((r) => r.todoId).filter((x): x is string => Boolean(x))),
);
const todoTitles = new Map<string, string>();
if (todoIds.length > 0) {
const tRows = await ctx.db
.select({ id: todo.id, title: todo.title })
.from(todo)
.where(inArray(todo.id, todoIds));
for (const t of tRows) todoTitles.set(t.id, t.title);
}
type Active = {
startedAt: string;
category: string;
todoId: string | null;
todoTitle: string | null;
description: string | null;
};
type Bucket = {
userId: string;
trackedSeconds: number; // Summe aller Task-Zeiten (Parallel-Tracking)
byCategory: Record<string, number>;
active: Active | null;
intervals: Array<readonly [number, number]>;
};
const now = Date.now();
const perUser = new Map<string, Bucket>();
for (const r of rows) {
const bucket: Bucket = perUser.get(r.userId) ?? {
userId: r.userId,
trackedSeconds: 0,
byCategory: {},
active: null,
intervals: [],
};
// Nur den heutigen Anteil zählen (über Mitternacht gelaufene Blöcke clampen).
const startMs = Math.max(r.startedAt.getTime(), dayStart);
const endMs = r.endedAt ? r.endedAt.getTime() : now;
const duration = Math.max(0, Math.round((endMs - startMs) / 1000));
bucket.trackedSeconds += duration;
bucket.byCategory[r.category] = (bucket.byCategory[r.category] ?? 0) + duration;
bucket.intervals.push([startMs, endMs]);
if (!r.endedAt) {
bucket.active = {
startedAt: r.startedAt.toISOString(),
category: r.category,
todoId: r.todoId,
todoTitle: r.todoId ? (todoTitles.get(r.todoId) ?? null) : null,
description: r.description,
};
}
perUser.set(r.userId, bucket);
}
// „Gesamt" pro Person = Wall-Clock (Vereinigung der Intervalle).
return Array.from(perUser.values()).map((b) => ({
userId: b.userId,
totalSeconds: unionSeconds(b.intervals),
trackedSeconds: b.trackedSeconds,
byCategory: b.byCategory,
active: b.active,
}));
}),
/**
* Team-Timeline: alle Zeit-Einträge eines Tages, pro Person eine Spur.
* Liefert Rohdaten (Start/Ende/Kategorie/Label); Achse & parallele Stränge
* (überlappende Blöcke) rendert das Frontend.
*/
teamTimeline: protectedProcedure
.input(TimeEntrySchemas.teamTimelineInput)
.query(async ({ ctx, input }) => {
const today = todayIso();
const date = input.date ?? today;
const isToday = date === today;
const onDate = (col: typeof timeEntry.startedAt | typeof timeEntry.endedAt) =>
sql`(${col} AT TIME ZONE 'Europe/Berlin')::date = ${date}`;
const cond = isToday
? sql`(${onDate(timeEntry.startedAt)} OR ${onDate(timeEntry.endedAt)} OR ${timeEntry.endedAt} IS NULL)`
: sql`(${onDate(timeEntry.startedAt)} OR ${onDate(timeEntry.endedAt)})`;
const rows = await ctx.db
.select()
.from(timeEntry)
.where(cond)
.orderBy(asc(timeEntry.startedAt));
const todoIds = Array.from(
new Set(rows.map((r) => r.todoId).filter((x): x is string => !!x)),
);
const titles = new Map<string, string>();
if (todoIds.length > 0) {
const tr = await ctx.db
.select({ id: todo.id, title: todo.title })
.from(todo)
.where(inArray(todo.id, todoIds));
for (const t of tr) titles.set(t.id, t.title);
}
const userRows = await ctx.db
.select({ id: user.id, name: user.name })
.from(user)
.where(eq(user.active, true));
const nameById = new Map(userRows.map((u) => [u.id, u.name]));
type Entry = {
id: string;
start: string;
end: string | null;
category: string;
description: string | null;
todoTitle: string | null;
};
const byUser = new Map<string, Entry[]>();
for (const r of rows) {
const arr = byUser.get(r.userId) ?? [];
arr.push({
id: r.id,
start: r.startedAt.toISOString(),
end: r.endedAt ? r.endedAt.toISOString() : null,
category: r.category,
description: r.description,
todoTitle: r.todoId ? (titles.get(r.todoId) ?? null) : null,
});
byUser.set(r.userId, arr);
}
const lanes = Array.from(byUser.entries())
.map(([userId, entries]) => ({ userId, name: nameById.get(userId) ?? '—', entries }))
.sort((a, b) => a.name.localeCompare(b.name));
return { date, lanes };
}),
/**
* Getrackte Zeit auf ein Projekt (time_entry mit bezugKind='project'):
* Gesamtsumme + Aufschlüsselung pro Person. bezugId wurde bislang erfasst,
* aber nirgends ausgewertet — das speist die „Getrackte Zeit"-Sektion im
* Projekt-Detail.
*/
byProject: protectedProcedure
.input(z.object({ projectId: z.string().uuid() }))
.query(async ({ ctx, input }) => {
const rows = await ctx.db
.select({
userId: timeEntry.userId,
seconds: sql<number>`COALESCE(SUM(${timeEntry.durationSeconds}), 0)`,
})
.from(timeEntry)
.where(and(eq(timeEntry.bezugKind, 'project'), eq(timeEntry.bezugId, input.projectId)))
.groupBy(timeEntry.userId);
const userRows = await ctx.db.select({ id: user.id, name: user.name }).from(user);
const nameById = new Map(userRows.map((u) => [u.id, u.name]));
const perUser = rows
.map((r) => ({
userId: r.userId,
name: nameById.get(r.userId) ?? '—',
seconds: Number(r.seconds),
}))
.filter((r) => r.seconds > 0)
.sort((a, b) => b.seconds - a.seconds);
const totalSeconds = perUser.reduce((sum, r) => sum + r.seconds, 0);
return { totalSeconds, perUser };
}),
});