import { and, eq, gte, lte } from 'drizzle-orm'; import { TRPCError } from '@trpc/server'; import { user, dayEntry, absenceDay } from '@cockpit/db'; import type { Db } from '@cockpit/db'; import { DayEntrySchemas } from '@cockpit/shared'; import { router, protectedProcedure } from '../trpc.js'; import { todayIso, isWerktag, parseIsoDate, formatIsoDate } from '../lib/werktag.js'; import { countStreakDays } from '../lib/streak.js'; async function computeStreak(db: Db, userId: string): Promise { const today = todayIso(); // DayEntries + Abwesenheiten der letzten 400 Tage (deckt > 1 Jahr Werktage ab, // damit lange Streaks nicht am Lookback-Fenster abgeschnitten werden). const endIso = today; const start = parseIsoDate(today); start.setUTCDate(start.getUTCDate() - 400); const startIso = formatIsoDate(start); const [entries, absences] = await Promise.all([ db .select({ date: dayEntry.date, status: dayEntry.status }) .from(dayEntry) .where( and(eq(dayEntry.userId, userId), gte(dayEntry.date, startIso), lte(dayEntry.date, endIso)), ), db .select({ date: absenceDay.date }) .from(absenceDay) .where( and( eq(absenceDay.userId, userId), gte(absenceDay.date, startIso), lte(absenceDay.date, endIso), ), ), ]); const fullDates = new Set(); for (const e of entries) if (e.status === 'full') fullDates.add(e.date); const absenceDates = new Set(absences.map((a) => a.date)); return countStreakDays({ today, fullDates, absenceDates }); } export const userRouter = router({ me: protectedProcedure.query(async ({ ctx }) => { const streak = await computeStreak(ctx.db, ctx.user.id); return { id: ctx.user.id, name: ctx.user.name, email: ctx.user.email, streak, }; }), list: protectedProcedure.query(async ({ ctx }) => { const rows = await ctx.db .select({ id: user.id, name: user.name, email: user.email }) .from(user) .where(eq(user.active, true)); return rows; }), markAbsent: protectedProcedure .input(DayEntrySchemas.markAbsentInput) .mutation(async ({ ctx, input }) => { if (input.to < input.from) { throw new TRPCError({ code: 'BAD_REQUEST', message: 'Endedatum vor Anfangsdatum.' }); } // Enumeriere Werktage zwischen from und to (inkl.) und füge sie als absence_day ein. let cursor = input.from; const toInsert: { userId: string; date: string; reason: 'urlaub' | 'krank' | 'sonstiges' }[] = []; while (cursor <= input.to) { if (isWerktag(cursor)) { toInsert.push({ userId: ctx.user.id, date: cursor, reason: input.reason }); } const next = parseIsoDate(cursor); next.setUTCDate(next.getUTCDate() + 1); cursor = formatIsoDate(next); } if (toInsert.length === 0) return { inserted: 0 }; await ctx.db.insert(absenceDay).values(toInsert).onConflictDoNothing(); return { inserted: toInsert.length }; }), });