// Pflicht-Minimum-Berechnung (Leitfaden §9). // Punkte 1–4 + 6 werden manuell in der App gepflegt; Punkt 5 (Status-Ampel aktuell) // wird hier zeitabhängig berechnet und im Cron aktualisiert. import { eq, desc } from 'drizzle-orm'; import { project, projectStatus } from '@cockpit/db'; import type { Db } from '@cockpit/db'; import { werktageBetween, todayIso, formatIsoDate } from './werktag.js'; const MAX_AGE_WERKTAGE = 7; export async function recomputePflichtMinimumStatusActual(db: Db): Promise<{ updated: number }> { const projects = await db.select().from(project).where(eq(project.archiviert, false)); const today = todayIso(); let updated = 0; for (const p of projects) { // Jüngsten Statusbericht DIESES Projekts heranziehen (statt global). const last = ( await db .select({ createdAt: projectStatus.createdAt }) .from(projectStatus) .where(eq(projectStatus.projectId, p.id)) .orderBy(desc(projectStatus.createdAt)) .limit(1) )[0]; const actual = last ? werktageBetween(formatIsoDate(last.createdAt), today) <= MAX_AGE_WERKTAGE : false; const newState = { ...p.pflichtMinimumState, status_aktuell: actual }; if (JSON.stringify(newState) !== JSON.stringify(p.pflichtMinimumState)) { await db.update(project).set({ pflichtMinimumState: newState }).where(eq(project.id, p.id)); updated++; } } return { updated }; }