Reports/Export builder (CSV/XLSX), plus a security fix pass
Adds the Berichte export pipeline (/api/export/{report,events,employees})
with shared CSV/XLSX writers in lib/export.ts and lib/reports-data.ts.
Security pass alongside it: sanitize .or() search terms against PostgREST
filter injection, sanitize spreadsheet cells against CSV/Excel formula
injection, stop leaking raw DB error messages to clients, harden the
service-role client with server-only, add baseline security headers, and
bump the vulnerable nested postcss via an override.
This commit is contained in:
@@ -2,6 +2,7 @@ import Link from "next/link";
|
||||
import { Suspense } from "react";
|
||||
import { AuditFilters } from "@/components/audit/AuditFilters";
|
||||
import { actionBadgeStyle } from "@/lib/colors";
|
||||
import { sanitizeIlikeTerm } from "@/lib/supabase/query";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
|
||||
const PAGE_SIZE = 25;
|
||||
@@ -38,7 +39,7 @@ export default async function AuditPage({ searchParams }: { searchParams: Promis
|
||||
|
||||
if (params.action) query = query.eq("action", params.action);
|
||||
if (params.q) {
|
||||
const q = params.q.trim();
|
||||
const q = sanitizeIlikeTerm(params.q.trim());
|
||||
query = query.or(`target_label.ilike.%${q}%,details.ilike.%${q}%,actor_name.ilike.%${q}%`);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Avatar } from "@/components/ui/Avatar";
|
||||
import { StatusChip } from "@/components/ui/StatusChip";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import { breadcrumbFor, loadOrgMaps } from "@/lib/org";
|
||||
import { sanitizeIlikeTerm } from "@/lib/supabase/query";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import type { EmploymentStatus } from "@/lib/supabase/types";
|
||||
|
||||
@@ -49,7 +50,8 @@ export default async function EmployeesPage({ searchParams }: EmployeesPageProps
|
||||
if (/^\d+$/.test(q)) {
|
||||
query = query.eq("personnel_number", Number(q));
|
||||
} else {
|
||||
query = query.or(`first_name.ilike.%${q}%,last_name.ilike.%${q}%,job_title.ilike.%${q}%`);
|
||||
const term = sanitizeIlikeTerm(q);
|
||||
query = query.or(`first_name.ilike.%${term}%,last_name.ilike.%${term}%,job_title.ilike.%${term}%`);
|
||||
}
|
||||
}
|
||||
if (params.division) query = query.eq("division_id", params.division);
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import { Suspense } from "react";
|
||||
import { ReportsPageClient } from "@/components/reports/ReportsPageClient";
|
||||
import {
|
||||
aggregateReport,
|
||||
DATE_SCOPED_MEASURES,
|
||||
type GroupDimension,
|
||||
type Measure,
|
||||
type OrgLookups,
|
||||
type ReportEmployee,
|
||||
} from "@/lib/reports";
|
||||
import { aggregateEvents, aggregateReport, sumValues, totalForRows, type EventGroupDimension, type GroupDimension, type Measure } from "@/lib/reports";
|
||||
import { loadEventHistory, loadOrgLookups, loadSnapshotEmployees } from "@/lib/reports-data";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import type { EmploymentStatus, EmploymentType } from "@/lib/supabase/types";
|
||||
import type { HistoryEventType } from "@/lib/supabase/types";
|
||||
|
||||
type SearchParams = {
|
||||
mode?: string;
|
||||
measure?: string;
|
||||
group?: string;
|
||||
split?: string;
|
||||
@@ -19,6 +14,8 @@ type SearchParams = {
|
||||
location?: string;
|
||||
status?: string;
|
||||
employment?: string;
|
||||
asOf?: string;
|
||||
eventType?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
};
|
||||
@@ -26,92 +23,78 @@ type SearchParams = {
|
||||
export default async function ReportsPage({ searchParams }: { searchParams: Promise<SearchParams> }) {
|
||||
const params = await searchParams;
|
||||
const supabase = await createClient();
|
||||
const mode = params.mode === "events" ? "events" : "snapshot";
|
||||
|
||||
const measure = (params.measure as Measure) || "headcount";
|
||||
const group = (params.group as GroupDimension) || "division";
|
||||
const split = (params.split as GroupDimension) || undefined;
|
||||
|
||||
const [{ data: divisions }, { data: departments }, { data: teams }, { data: locations }] = await Promise.all([
|
||||
supabase.from("divisions").select("id, name").order("name"),
|
||||
supabase.from("departments").select("id, name"),
|
||||
supabase.from("teams").select("id, name, department_id"),
|
||||
supabase.from("locations").select("id, name").order("name"),
|
||||
]);
|
||||
|
||||
const departmentNameById = new Map((departments ?? []).map((d) => [d.id, d.name]));
|
||||
const lookups: OrgLookups = {
|
||||
divisionName: new Map((divisions ?? []).map((d) => [d.id, d.name])),
|
||||
departmentNameByTeam: new Map((teams ?? []).map((t) => [t.id, departmentNameById.get(t.department_id) ?? "Unbekannt"])),
|
||||
teamName: new Map((teams ?? []).map((t) => [t.id, t.name])),
|
||||
locationName: new Map((locations ?? []).map((l) => [l.id, l.name])),
|
||||
};
|
||||
|
||||
let query = supabase
|
||||
.from("employees")
|
||||
.select(
|
||||
"id, first_name, last_name, job_title, division_id, team_id, location_id, status, employment_type, contract_type, entry_date, exit_date, weekly_hours, source, paygrade, birth_date, gender"
|
||||
);
|
||||
|
||||
if (params.division) query = query.eq("division_id", params.division);
|
||||
if (params.location) query = query.eq("location_id", params.location);
|
||||
if (params.status) query = query.eq("status", params.status as EmploymentStatus);
|
||||
if (params.employment) query = query.eq("employment_type", params.employment as EmploymentType);
|
||||
|
||||
const isDateScoped = DATE_SCOPED_MEASURES.includes(measure);
|
||||
const currentYear = new Date().getFullYear();
|
||||
const from = params.from || `${currentYear}-01-01`;
|
||||
const to = params.to || `${currentYear}-12-31`;
|
||||
if (isDateScoped) {
|
||||
if (measure === "hires") query = query.gte("entry_date", from).lte("entry_date", to);
|
||||
else query = query.gte("exit_date", from).lte("exit_date", to).not("exit_date", "is", null);
|
||||
} else if (!params.status) {
|
||||
query = query.in("status", ["Aktiv", "Karenz"]);
|
||||
}
|
||||
|
||||
const { data: employeesData } = await query;
|
||||
const employees = (employeesData ?? []) as ReportEmployee[];
|
||||
|
||||
const rows = aggregateReport(employees, measure, group, split ?? null, lookups);
|
||||
const total = measureValueForTotal(rows, measure);
|
||||
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
const [{ lookups, divisions, locations }, { data: userRes }] = await Promise.all([loadOrgLookups(supabase), supabase.auth.getUser()]);
|
||||
const user = userRes.user;
|
||||
const { data: savedReports } = user
|
||||
? await supabase.from("saved_reports").select("id, name, config").eq("created_by", user.id).order("created_at", { ascending: false })
|
||||
: { data: [] };
|
||||
|
||||
if (mode === "events") {
|
||||
const group = (params.group as EventGroupDimension) || "event_type";
|
||||
const split = (params.split as EventGroupDimension) || undefined;
|
||||
const eventType = (params.eventType as HistoryEventType) || undefined;
|
||||
|
||||
const events = await loadEventHistory(supabase, { eventType, division: params.division, location: params.location, from: params.from, to: params.to });
|
||||
const rows = aggregateEvents(events, group, split ?? null, lookups);
|
||||
const total = sumValues(rows);
|
||||
|
||||
return (
|
||||
<Suspense>
|
||||
<ReportsPageClient
|
||||
mode="events"
|
||||
eventGroup={group}
|
||||
eventSplit={split ?? ""}
|
||||
eventType={eventType ?? ""}
|
||||
eventFilters={{ division: params.division ?? "", location: params.location ?? "", from: params.from ?? "", to: params.to ?? "" }}
|
||||
rows={rows}
|
||||
total={total}
|
||||
recordCount={events.length}
|
||||
divisions={divisions}
|
||||
locations={locations}
|
||||
savedReports={savedReports ?? []}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
const measure = (params.measure as Measure) || "headcount";
|
||||
const group = (params.group as GroupDimension) || "division";
|
||||
const split = (params.split as GroupDimension) || undefined;
|
||||
const asOf = params.asOf || undefined;
|
||||
|
||||
const employees = await loadSnapshotEmployees(supabase, {
|
||||
division: params.division,
|
||||
location: params.location,
|
||||
status: params.status,
|
||||
employment: params.employment,
|
||||
asOf,
|
||||
});
|
||||
const rows = aggregateReport(employees, measure, group, split ?? null, lookups, asOf);
|
||||
const total = totalForRows(rows, measure);
|
||||
|
||||
return (
|
||||
<Suspense>
|
||||
<ReportsPageClient
|
||||
mode="snapshot"
|
||||
measure={measure}
|
||||
group={group}
|
||||
split={split ?? ""}
|
||||
asOf={asOf ?? ""}
|
||||
filters={{
|
||||
division: params.division ?? "",
|
||||
location: params.location ?? "",
|
||||
status: params.status ?? "",
|
||||
employment: params.employment ?? "",
|
||||
from: params.from ?? "",
|
||||
to: params.to ?? "",
|
||||
}}
|
||||
rows={rows}
|
||||
total={total}
|
||||
recordCount={employees.length}
|
||||
divisions={divisions ?? []}
|
||||
locations={locations ?? []}
|
||||
divisions={divisions}
|
||||
locations={locations}
|
||||
savedReports={savedReports ?? []}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function measureValueForTotal(rows: { value: number; count: number }[], measure: Measure): number {
|
||||
if (["headcount", "fte", "hires", "exits"].includes(measure)) {
|
||||
return rows.reduce((s, r) => s + r.value, 0);
|
||||
}
|
||||
// averages/ratios: weight by underlying count for a sensible overall figure
|
||||
const totalCount = rows.reduce((s, r) => s + r.count, 0);
|
||||
if (totalCount === 0) return 0;
|
||||
return rows.reduce((s, r) => s + r.value * r.count, 0) / totalCount;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,8 @@ export async function GET(request: NextRequest) {
|
||||
const { data, error } = await supabase.rpc("apply_due_pending_changes");
|
||||
|
||||
if (error) {
|
||||
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||
console.error("apply_due_pending_changes failed:", error);
|
||||
return NextResponse.json({ error: "Interner Fehler." }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ applied: data });
|
||||
|
||||
105
app/api/export/employees/route.ts
Normal file
105
app/api/export/employees/route.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn } from "@/lib/export";
|
||||
import { deriveStatusAsOf, parseStatuses, type OrgLookups } from "@/lib/reports";
|
||||
import { loadOrgLookups, type ReportFilters } from "@/lib/reports-data";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import type { Database, EmploymentType } from "@/lib/supabase/types";
|
||||
|
||||
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
|
||||
|
||||
// Full raw data dump — every column on `employees`, not just the fields a
|
||||
// pivot report groups by. Respects the same division/location/status/
|
||||
// employment filters as the Berichte page. With `asOf` (Stichtag), status
|
||||
// filtering happens against the *derived* status as of that date rather
|
||||
// than the live `status` column — see deriveStatusAsOf.
|
||||
export async function GET(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
|
||||
|
||||
const { data: profile } = await supabase.from("profiles").select("role, is_active").eq("id", user.id).maybeSingle();
|
||||
if (profile?.role !== "hr" || profile?.is_active !== true) {
|
||||
return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
|
||||
}
|
||||
|
||||
const params = request.nextUrl.searchParams;
|
||||
const format = params.get("format") === "xlsx" ? "xlsx" : "csv";
|
||||
const asOf = params.get("asOf") ?? undefined;
|
||||
const filters: ReportFilters = {
|
||||
division: params.get("division") ?? undefined,
|
||||
location: params.get("location") ?? undefined,
|
||||
status: params.get("status") ?? undefined,
|
||||
employment: params.get("employment") ?? undefined,
|
||||
};
|
||||
|
||||
const statuses = parseStatuses(filters.status);
|
||||
|
||||
let query = supabase.from("employees").select("*").order("last_name");
|
||||
if (filters.division) query = query.eq("division_id", filters.division);
|
||||
if (filters.location) query = query.eq("location_id", filters.location);
|
||||
if (filters.employment) query = query.eq("employment_type", filters.employment as EmploymentType);
|
||||
if (!asOf) query = query.in("status", statuses);
|
||||
|
||||
const [{ data: employees, error }, { lookups }, { data: allEmployees }] = await Promise.all([
|
||||
query,
|
||||
loadOrgLookups(supabase),
|
||||
supabase.from("employees").select("id, first_name, last_name"),
|
||||
]);
|
||||
if (error) {
|
||||
console.error("employees export query failed:", error);
|
||||
return NextResponse.json({ error: "Interner Fehler." }, { status: 500 });
|
||||
}
|
||||
|
||||
const managerName = new Map((allEmployees ?? []).map((e) => [e.id, `${e.first_name} ${e.last_name}`]));
|
||||
const rows = asOf ? (employees ?? []).filter((e) => statuses.includes(deriveStatusAsOf(e, asOf))) : (employees ?? []);
|
||||
const columns = employeeExportColumns(lookups, managerName, asOf);
|
||||
const filename = exportFilename("mitarbeiter-export", format);
|
||||
|
||||
const body = format === "xlsx" ? await toXlsx(rows, columns, "Mitarbeiter") : toCsv(rows, columns);
|
||||
// TS 5.9's Uint8Array<ArrayBufferLike> vs DOM's BlobPart/ArrayBuffer<> generic
|
||||
// mismatch (microsoft/TypeScript#59417) — a real Uint8Array works fine here.
|
||||
return new NextResponse(new Blob([body as BlobPart]), { headers: exportResponseHeaders(filename, format) });
|
||||
}
|
||||
|
||||
function employeeExportColumns(lookups: OrgLookups, managerName: Map<string, string>, asOf?: string): ExportColumn<EmployeeRow>[] {
|
||||
const columns: ExportColumn<EmployeeRow>[] = [
|
||||
{ header: "Pers.-Nr.", get: (e) => e.personnel_number },
|
||||
{ header: "Vorname", get: (e) => e.first_name },
|
||||
{ header: "Nachname", get: (e) => e.last_name },
|
||||
{ header: "Geschlecht", get: (e) => (e.gender === "m" ? "männlich" : "weiblich") },
|
||||
{ header: "Geburtsdatum", get: (e) => e.birth_date, kind: "date" },
|
||||
{ header: "SV-Nummer", get: (e) => e.sv_nummer },
|
||||
{ header: "Staatsbürgerschaft", get: (e) => e.nationality },
|
||||
{ header: "Adresse", get: (e) => e.address },
|
||||
{ header: "Wohnsitzland", get: (e) => e.address_country },
|
||||
{ header: "E-Mail", get: (e) => e.email },
|
||||
{ header: "Telefon", get: (e) => e.phone },
|
||||
{ header: "Bereich", get: (e) => lookups.divisionName.get(e.division_id) ?? "" },
|
||||
{ header: "Abteilung", get: (e) => (e.team_id ? (lookups.departmentNameByTeam.get(e.team_id) ?? "") : "") },
|
||||
{ header: "Team", get: (e) => (e.team_id ? (lookups.teamName.get(e.team_id) ?? "") : "") },
|
||||
{ header: "Standort", get: (e) => lookups.locationName.get(e.location_id) ?? "" },
|
||||
{ header: "Position", get: (e) => e.job_title },
|
||||
{ header: "Vorgesetzte:r", get: (e) => (e.manager_id ? (managerName.get(e.manager_id) ?? "") : "") },
|
||||
{ header: "Führungskraft", get: (e) => e.is_lead },
|
||||
{ header: "Org-Level", get: (e) => e.org_level },
|
||||
{ header: "Beschäftigungsausmaß", get: (e) => e.employment_type },
|
||||
{ header: "Wochenstunden", get: (e) => e.weekly_hours },
|
||||
{ header: "Vertragsart", get: (e) => e.contract_type },
|
||||
{ header: "Befristet bis", get: (e) => e.contract_end_date, kind: "date" },
|
||||
{ header: "Paygrade", get: (e) => e.paygrade },
|
||||
{ header: "Herkunft", get: (e) => e.source },
|
||||
{ header: "Status", get: (e) => e.status },
|
||||
{ header: "Eintrittsdatum", get: (e) => e.entry_date, kind: "date" },
|
||||
{ header: "Austrittsdatum", get: (e) => e.exit_date, kind: "date" },
|
||||
{ header: "Austrittsgrund", get: (e) => e.exit_reason },
|
||||
{ header: "Karenzbeginn", get: (e) => e.karenz_start_date, kind: "date" },
|
||||
{ header: "Karenz-Rückkehrdatum", get: (e) => e.karenz_return_date, kind: "date" },
|
||||
];
|
||||
if (asOf) {
|
||||
const statusIndex = columns.findIndex((c) => c.header === "Status");
|
||||
columns.splice(statusIndex + 1, 0, { header: `Status zum Stichtag (${asOf})`, get: (e) => deriveStatusAsOf(e, asOf) });
|
||||
}
|
||||
return columns;
|
||||
}
|
||||
62
app/api/export/events/route.ts
Normal file
62
app/api/export/events/route.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn } from "@/lib/export";
|
||||
import { EVENT_TYPE_LABELS, type OrgLookups, type ReportEvent } from "@/lib/reports";
|
||||
import { loadEventHistory, loadOrgLookups } from "@/lib/reports-data";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import type { HistoryEventType } from "@/lib/supabase/types";
|
||||
|
||||
// Full raw event-log dump — one row per employee_history entry in the
|
||||
// selected period (default: current year), every event type unless one is
|
||||
// picked, org columns resolved from each affected employee's current
|
||||
// placement (see loadEventHistory).
|
||||
export async function GET(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
|
||||
|
||||
const { data: profile } = await supabase.from("profiles").select("role, is_active").eq("id", user.id).maybeSingle();
|
||||
if (profile?.role !== "hr" || profile?.is_active !== true) {
|
||||
return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
|
||||
}
|
||||
|
||||
const params = request.nextUrl.searchParams;
|
||||
const format = params.get("format") === "xlsx" ? "xlsx" : "csv";
|
||||
const eventType = (params.get("eventType") as HistoryEventType) || undefined;
|
||||
const from = params.get("from") ?? undefined;
|
||||
const to = params.get("to") ?? undefined;
|
||||
|
||||
const [{ lookups }, events] = await Promise.all([
|
||||
loadOrgLookups(supabase),
|
||||
loadEventHistory(supabase, {
|
||||
eventType,
|
||||
division: params.get("division") ?? undefined,
|
||||
location: params.get("location") ?? undefined,
|
||||
from,
|
||||
to,
|
||||
}),
|
||||
]);
|
||||
|
||||
const columns = eventExportColumns(lookups);
|
||||
const filename = exportFilename(`ereignisse-${eventType ?? "alle"}`, format);
|
||||
const body = format === "xlsx" ? await toXlsx(events, columns, "Ereignisse") : toCsv(events, columns);
|
||||
// TS 5.9's Uint8Array<ArrayBufferLike> vs DOM's BlobPart/ArrayBuffer<> generic
|
||||
// mismatch (microsoft/TypeScript#59417) — a real Uint8Array works fine here.
|
||||
return new NextResponse(new Blob([body as BlobPart]), { headers: exportResponseHeaders(filename, format) });
|
||||
}
|
||||
|
||||
function eventExportColumns(lookups: OrgLookups): ExportColumn<ReportEvent>[] {
|
||||
return [
|
||||
{ header: "Datum", get: (e) => e.event_date, kind: "date" },
|
||||
{ header: "Ereignistyp", get: (e) => EVENT_TYPE_LABELS[e.event_type] ?? e.event_type },
|
||||
{ header: "Vorname", get: (e) => e.first_name },
|
||||
{ header: "Nachname", get: (e) => e.last_name },
|
||||
{ header: "Position", get: (e) => e.job_title },
|
||||
{ header: "Bereich", get: (e) => lookups.divisionName.get(e.division_id) ?? "" },
|
||||
{ header: "Abteilung", get: (e) => (e.team_id ? (lookups.departmentNameByTeam.get(e.team_id) ?? "") : "") },
|
||||
{ header: "Team", get: (e) => (e.team_id ? (lookups.teamName.get(e.team_id) ?? "") : "") },
|
||||
{ header: "Standort", get: (e) => lookups.locationName.get(e.location_id) ?? "" },
|
||||
{ header: "Beschreibung", get: (e) => e.description },
|
||||
];
|
||||
}
|
||||
123
app/api/export/report/route.ts
Normal file
123
app/api/export/report/route.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn } from "@/lib/export";
|
||||
import {
|
||||
aggregateEvents,
|
||||
aggregateReport,
|
||||
EVENT_GROUP_LABELS,
|
||||
GROUP_LABELS,
|
||||
MEASURE_LABELS,
|
||||
sumValues,
|
||||
totalForRows,
|
||||
type EventGroupDimension,
|
||||
type GroupDimension,
|
||||
type Measure,
|
||||
type ReportRow,
|
||||
} from "@/lib/reports";
|
||||
import { loadEventHistory, loadOrgLookups, loadSnapshotEmployees } from "@/lib/reports-data";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import type { HistoryEventType } from "@/lib/supabase/types";
|
||||
|
||||
// Exports exactly the pivot table currently on screen (same mode/measure or
|
||||
// event-type/group/split/filters, read from the query string the client
|
||||
// already keeps in the URL) as a flat table — one row per group, one column
|
||||
// per split value if a split is active.
|
||||
export async function GET(request: NextRequest) {
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
} = await supabase.auth.getUser();
|
||||
if (!user) return NextResponse.json({ error: "Nicht angemeldet." }, { status: 401 });
|
||||
|
||||
const { data: profile } = await supabase.from("profiles").select("role, is_active").eq("id", user.id).maybeSingle();
|
||||
if (profile?.role !== "hr" || profile?.is_active !== true) {
|
||||
return NextResponse.json({ error: "Nicht berechtigt." }, { status: 403 });
|
||||
}
|
||||
|
||||
const params = request.nextUrl.searchParams;
|
||||
const format = params.get("format") === "xlsx" ? "xlsx" : "csv";
|
||||
const mode = params.get("mode") === "events" ? "events" : "snapshot";
|
||||
const { lookups } = await loadOrgLookups(supabase);
|
||||
|
||||
let rows: ReportRow[];
|
||||
let columns: ExportColumn<ReportRow>[];
|
||||
let filenameBase: string;
|
||||
|
||||
if (mode === "events") {
|
||||
const group = (params.get("group") as EventGroupDimension) || "event_type";
|
||||
const split = (params.get("split") as EventGroupDimension) || null;
|
||||
const eventType = (params.get("eventType") as HistoryEventType) || undefined;
|
||||
const events = await loadEventHistory(supabase, {
|
||||
eventType,
|
||||
division: params.get("division") ?? undefined,
|
||||
location: params.get("location") ?? undefined,
|
||||
from: params.get("from") ?? undefined,
|
||||
to: params.get("to") ?? undefined,
|
||||
});
|
||||
rows = aggregateEvents(events, group, split, lookups);
|
||||
columns = eventReportColumns(rows, group, split, sumValues(rows));
|
||||
filenameBase = `ereignisse-${eventType ?? "alle"}-${group}`;
|
||||
} else {
|
||||
const measure = (params.get("measure") as Measure) || "headcount";
|
||||
const group = (params.get("group") as GroupDimension) || "division";
|
||||
const split = (params.get("split") as GroupDimension) || null;
|
||||
const asOf = params.get("asOf") ?? undefined;
|
||||
const employees = await loadSnapshotEmployees(supabase, {
|
||||
division: params.get("division") ?? undefined,
|
||||
location: params.get("location") ?? undefined,
|
||||
status: params.get("status") ?? undefined,
|
||||
employment: params.get("employment") ?? undefined,
|
||||
asOf,
|
||||
});
|
||||
rows = aggregateReport(employees, measure, group, split, lookups, asOf);
|
||||
columns = snapshotReportColumns(rows, measure, group, split, totalForRows(rows, measure));
|
||||
filenameBase = `bericht-${measure}-${group}`;
|
||||
}
|
||||
|
||||
const filename = exportFilename(filenameBase, format);
|
||||
const body = format === "xlsx" ? await toXlsx(rows, columns, "Bericht") : toCsv(rows, columns);
|
||||
// TS 5.9's Uint8Array<ArrayBufferLike> vs DOM's BlobPart/ArrayBuffer<> generic
|
||||
// mismatch (microsoft/TypeScript#59417) — a real Uint8Array works fine here.
|
||||
return new NextResponse(new Blob([body as BlobPart]), { headers: exportResponseHeaders(filename, format) });
|
||||
}
|
||||
|
||||
function snapshotReportColumns(
|
||||
rows: ReportRow[],
|
||||
measure: Measure,
|
||||
group: GroupDimension,
|
||||
split: GroupDimension | null,
|
||||
total: number
|
||||
): ExportColumn<ReportRow>[] {
|
||||
const columns: ExportColumn<ReportRow>[] = [{ header: GROUP_LABELS[group], get: (r) => r.key }];
|
||||
if (split) {
|
||||
const splitKeys = Array.from(new Set(rows.flatMap((r) => r.split?.map((s) => s.key) ?? [])));
|
||||
for (const key of splitKeys) {
|
||||
columns.push({ header: key, get: (r) => Math.round((r.split?.find((s) => s.key === key)?.value ?? 0) * 100) / 100 });
|
||||
}
|
||||
}
|
||||
columns.push(
|
||||
{ header: MEASURE_LABELS[measure], get: (r) => Math.round(r.value * 100) / 100 },
|
||||
{ header: "Anzahl", get: (r) => r.count },
|
||||
{ header: "Anteil (%)", get: (r) => (total > 0 ? Math.round((r.value / total) * 1000) / 10 : 0) }
|
||||
);
|
||||
return columns;
|
||||
}
|
||||
|
||||
function eventReportColumns(
|
||||
rows: ReportRow[],
|
||||
group: EventGroupDimension,
|
||||
split: EventGroupDimension | null,
|
||||
total: number
|
||||
): ExportColumn<ReportRow>[] {
|
||||
const columns: ExportColumn<ReportRow>[] = [{ header: EVENT_GROUP_LABELS[group], get: (r) => r.key }];
|
||||
if (split) {
|
||||
const splitKeys = Array.from(new Set(rows.flatMap((r) => r.split?.map((s) => s.key) ?? [])));
|
||||
for (const key of splitKeys) {
|
||||
columns.push({ header: key, get: (r) => r.split?.find((s) => s.key === key)?.value ?? 0 });
|
||||
}
|
||||
}
|
||||
columns.push(
|
||||
{ header: "Anzahl", get: (r) => r.count },
|
||||
{ header: "Anteil (%)", get: (r) => (total > 0 ? Math.round((r.value / total) * 1000) / 10 : 0) }
|
||||
);
|
||||
return columns;
|
||||
}
|
||||
Reference in New Issue
Block a user