import { createClient } from "@/lib/supabase/server"; import { loadProfile } from "@/lib/auth/profile"; import { kannAuditLogSehen } from "@/lib/auth/roles"; import { auditCsv } from "@/lib/audit/csv"; import type { AuditEintrag } from "@/lib/audit/bezeichnungen"; import { parseAuditFilter } from "@/lib/audit/filter"; import { ladeAuditLog } from "@/lib/audit/queries"; export const dynamic = "force-dynamic"; const MAX_ZEILEN = 10_000; export async function GET(request: Request): Promise { const profil = await loadProfile(); if (profil.status !== "ok" || !kannAuditLogSehen(profil.profile.role)) { return new Response("Keine Berechtigung", { status: 403 }); } const params = Object.fromEntries(new URL(request.url).searchParams); const filter = parseAuditFilter(params); const supabase = await createClient(); const zugriff = { role: profil.profile.role, firmaId: profil.profile.firma_id }; const { data: nutzer, error: nutzerFehler } = await supabase.from("profiles").select("id, name"); if (nutzerFehler) { throw new Error(`Nutzer laden fehlgeschlagen: ${nutzerFehler.message}`); } const namen = new Map((nutzer ?? []).map((n) => [n.id as string, n.name as string])); // PostgREST begrenzt die Antwort je Anfrage (max_rows, Standard 1000): // deshalb in Bloecken laden. const eintraege: AuditEintrag[] = []; for (let offset = 0; offset < MAX_ZEILEN; offset += 1000) { const block = await ladeAuditLog(supabase, zugriff, filter, { limit: Math.min(1000, MAX_ZEILEN - offset), offset }); eintraege.push(...block); if (block.length < 1000) break; } // sv-SE liefert YYYY-MM-DD; Datum in Berliner Zeit. const datum = new Intl.DateTimeFormat("sv-SE", { timeZone: "Europe/Berlin" }).format(new Date()); return new Response(auditCsv(eintraege, namen), { headers: { "Content-Type": "text/csv; charset=utf-8", "Content-Disposition": `attachment; filename="audit-log-${datum}.csv"`, "Cache-Control": "no-store", }, }); }