import { TRPCError } from '@trpc/server'; import { z } from 'zod'; import { and, eq, isNull, desc, sql, inArray } from 'drizzle-orm'; import { timeEntry, dayEntry, todo, type TimeEntry } 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): 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 stopCurrent( tx: import('@cockpit/db').Db, userId: string, now: Date, ): Promise { const active = ( await tx .select() .from(timeEntry) .where(and(eq(timeEntry.userId, userId), isNull(timeEntry.endedAt))) .limit(1) )[0]; if (!active) return null; const durationSeconds = Math.max(0, Math.round((now.getTime() - active.startedAt.getTime()) / 1000)); const [stopped] = await tx .update(timeEntry) .set({ endedAt: now, durationSeconds, updatedAt: now }) .where(eq(timeEntry.id, active.id)) .returning(); return stopped ?? null; } async function findCurrentDayEntryId( db: import('@cockpit/db').Db, userId: string, ): Promise { 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({ /** * Aktiver Eintrag (oder null) für den eingeloggten User. */ now: protectedProcedure.query(async ({ ctx }) => { const row = ( await ctx.db .select() .from(timeEntry) .where(and(eq(timeEntry.userId, ctx.user.id), isNull(timeEntry.endedAt))) .limit(1) )[0]; if (!row) return null; // ToDo-Titel auch dann auflösen, wenn der Timer über Mitternacht läuft und // das ToDo nicht mehr in der heutigen Liste steht. let todoTitle: string | null = null; if (row.todoId) { const t = ( await ctx.db.select({ title: todo.title }).from(todo).where(eq(todo.id, row.todoId)).limit(1) )[0]; todoTitle = t?.title ?? null; } return { ...row, todoTitle }; }), /** * Startet einen neuen Eintrag; stoppt automatisch einen evtl. laufenden. */ start: protectedProcedure .input(TimeEntrySchemas.startTimeEntryInput) .mutation(async ({ ctx, input }) => { const now = new Date(); const dayEntryId = await findCurrentDayEntryId(ctx.db, ctx.user.id); const result = await ctx.db.transaction(async (tx) => { await stopCurrent(tx, ctx.user.id, now); const [created] = await tx .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; }); return result; }), /** * Stoppt den aktiven Eintrag. */ stop: protectedProcedure.mutation(async ({ ctx }) => { const now = new Date(); const stopped = await stopCurrent(ctx.db, ctx.user.id, now); if (!stopped) { throw new TRPCError({ code: 'BAD_REQUEST', message: 'Aktuell läuft kein Timer.' }); } 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(); 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(); 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; active: Active | null; intervals: Array; }; const now = Date.now(); const perUser = new Map(); 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, })); }), });