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:
@@ -1,6 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { sanitizeIlikeTerm } from "@/lib/supabase/query";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
import type { Database } from "@/lib/supabase/types";
|
||||
|
||||
@@ -122,7 +123,7 @@ export async function searchActiveEmployees(query: string): Promise<EmployeeSear
|
||||
.in("status", ["Aktiv", "Karenz"])
|
||||
.limit(20);
|
||||
if (query.trim()) {
|
||||
const term = query.trim();
|
||||
const term = sanitizeIlikeTerm(query.trim());
|
||||
q = q.or(`first_name.ilike.%${term}%,last_name.ilike.%${term}%,job_title.ilike.%${term}%`);
|
||||
}
|
||||
const { data } = await q;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use server";
|
||||
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { sanitizeIlikeTerm } from "@/lib/supabase/query";
|
||||
import { createClient } from "@/lib/supabase/server";
|
||||
|
||||
type ActionResult = { success: boolean; error?: string };
|
||||
@@ -49,7 +50,7 @@ export async function searchSuperiors(query: string, forLeadPosition: boolean):
|
||||
.limit(20);
|
||||
q = forLeadPosition ? q.lte("org_level", 1) : q.eq("is_lead", true).eq("org_level", 2);
|
||||
if (query.trim()) {
|
||||
const term = query.trim();
|
||||
const term = sanitizeIlikeTerm(query.trim());
|
||||
q = q.or(`first_name.ilike.%${term}%,last_name.ilike.%${term}%,job_title.ilike.%${term}%`);
|
||||
}
|
||||
const { data } = await q;
|
||||
|
||||
@@ -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
|
||||
measure={measure}
|
||||
group={group}
|
||||
split={split ?? ""}
|
||||
filters={{
|
||||
division: params.division ?? "",
|
||||
location: params.location ?? "",
|
||||
status: params.status ?? "",
|
||||
employment: params.employment ?? "",
|
||||
from: params.from ?? "",
|
||||
to: params.to ?? "",
|
||||
}}
|
||||
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={employees.length}
|
||||
divisions={divisions ?? []}
|
||||
locations={locations ?? []}
|
||||
recordCount={events.length}
|
||||
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;
|
||||
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 ?? "",
|
||||
}}
|
||||
rows={rows}
|
||||
total={total}
|
||||
recordCount={employees.length}
|
||||
divisions={divisions}
|
||||
locations={locations}
|
||||
savedReports={savedReports ?? []}
|
||||
/>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowRightLeft, Clock, Pencil, RotateCcw, TrendingUp, XCircle } from "lucide-react";
|
||||
import { ArrowLeft, ArrowRightLeft, Clock, Pencil, RotateCcw, TrendingUp, XCircle } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useState } from "react";
|
||||
import { Avatar } from "@/components/ui/Avatar";
|
||||
import { StatusChip } from "@/components/ui/StatusChip";
|
||||
@@ -56,6 +57,10 @@ export function EmployeeDetail(props: EmployeeDetailProps) {
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<Link href="/employees" className="flex w-fit items-center gap-1.5 text-sm font-semibold text-ink-muted hover:text-ink">
|
||||
<ArrowLeft className="h-4 w-4" /> Zurück zu Mitarbeiter:innen
|
||||
</Link>
|
||||
|
||||
<div className="rounded border border-border bg-white p-6">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { Download, Save, Trash2 } from "lucide-react";
|
||||
import { FileSpreadsheet, FileText, Save, Trash2 } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
@@ -10,34 +10,59 @@ import { useToast } from "@/components/ui/Toast";
|
||||
import { fmtDate } from "@/lib/format";
|
||||
import {
|
||||
AVERAGE_MEASURES,
|
||||
DATE_SCOPED_MEASURES,
|
||||
EVENT_DATE_OPEN,
|
||||
EVENT_GROUP_LABELS,
|
||||
EVENT_REPORT_PRESETS,
|
||||
EVENT_TYPE_LABELS,
|
||||
GROUP_LABELS,
|
||||
MEASURE_LABELS,
|
||||
parseStatuses,
|
||||
REPORT_PRESETS,
|
||||
STATUS_OPTIONS,
|
||||
todayIso,
|
||||
type EventGroupDimension,
|
||||
type GroupDimension,
|
||||
type Measure,
|
||||
type ReportRow,
|
||||
} from "@/lib/reports";
|
||||
import type { HistoryEventType } from "@/lib/supabase/types";
|
||||
|
||||
const SPLIT_COLORS = ["bg-brand-500", "bg-info-text", "bg-purple-text", "bg-warning-text", "bg-success-text", "bg-danger-solid"];
|
||||
const EVENT_TYPES = Object.keys(EVENT_TYPE_LABELS) as HistoryEventType[];
|
||||
|
||||
type SavedReport = { id: string; name: string; config: Record<string, unknown> };
|
||||
type OrgOption = { id: string; name: string };
|
||||
|
||||
type ReportsPageClientProps = {
|
||||
measure: Measure;
|
||||
group: GroupDimension;
|
||||
split: GroupDimension | "";
|
||||
filters: { division: string; location: string; status: string; employment: string; from: string; to: string };
|
||||
type CommonProps = {
|
||||
rows: ReportRow[];
|
||||
total: number;
|
||||
recordCount: number;
|
||||
divisions: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
divisions: OrgOption[];
|
||||
locations: OrgOption[];
|
||||
savedReports: SavedReport[];
|
||||
};
|
||||
|
||||
type SnapshotProps = CommonProps & {
|
||||
mode: "snapshot";
|
||||
measure: Measure;
|
||||
group: GroupDimension;
|
||||
split: GroupDimension | "";
|
||||
asOf: string;
|
||||
filters: { division: string; location: string; status: string; employment: string };
|
||||
};
|
||||
|
||||
type EventsProps = CommonProps & {
|
||||
mode: "events";
|
||||
eventGroup: EventGroupDimension;
|
||||
eventSplit: EventGroupDimension | "";
|
||||
eventType: string;
|
||||
eventFilters: { division: string; location: string; from: string; to: string };
|
||||
};
|
||||
|
||||
type ReportsPageClientProps = SnapshotProps | EventsProps;
|
||||
|
||||
function formatValue(measure: Measure, value: number): string {
|
||||
if (["headcount", "hires", "exits"].includes(measure)) return String(Math.round(value));
|
||||
if (measure === "headcount") return String(Math.round(value));
|
||||
if (measure === "fte") return value.toFixed(1);
|
||||
if (measure === "parttime_rate" || measure === "female_share") return `${value.toFixed(1)}%`;
|
||||
if (measure === "avg_age" || measure === "avg_tenure") return `${value.toFixed(1)} Jahre`;
|
||||
@@ -45,7 +70,7 @@ function formatValue(measure: Measure, value: number): string {
|
||||
}
|
||||
|
||||
export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
const { measure, group, split, filters, rows, total, recordCount, divisions, locations, savedReports } = props;
|
||||
const { mode, rows, total, recordCount, divisions, locations, savedReports } = props;
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
@@ -64,8 +89,24 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
router.push(`${pathname}?${sp.toString()}`);
|
||||
}
|
||||
|
||||
function applyPreset(preset: (typeof REPORT_PRESETS)[number]) {
|
||||
router.push(`${pathname}?measure=${preset.measure}&group=${preset.group}${preset.split ? `&split=${preset.split}` : ""}`);
|
||||
function switchMode(next: "snapshot" | "events") {
|
||||
router.push(`${pathname}?mode=${next}`);
|
||||
}
|
||||
|
||||
function toggleStatus(status: string) {
|
||||
if (mode !== "snapshot") return;
|
||||
const current = parseStatuses(props.filters.status);
|
||||
const next = current.includes(status as (typeof current)[number]) ? current.filter((s) => s !== status) : [...current, status];
|
||||
updateParams({ status: next.length > 0 ? next.join(",") : undefined });
|
||||
}
|
||||
|
||||
function applyPreset(preset: { group: string; split?: string; eventType?: string; measure?: string }) {
|
||||
const sp = new URLSearchParams({ mode });
|
||||
if (preset.measure) sp.set("measure", preset.measure);
|
||||
sp.set("group", preset.group);
|
||||
if (preset.split) sp.set("split", preset.split);
|
||||
if (preset.eventType) sp.set("eventType", preset.eventType);
|
||||
router.push(`${pathname}?${sp.toString()}`);
|
||||
}
|
||||
|
||||
function applySavedReport(config: Record<string, unknown>) {
|
||||
@@ -73,6 +114,7 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
for (const [k, v] of Object.entries(config)) {
|
||||
if (typeof v === "string" && v) sp.set(k, v);
|
||||
}
|
||||
if (!sp.get("mode")) sp.set("mode", "snapshot");
|
||||
router.push(`${pathname}?${sp.toString()}`);
|
||||
}
|
||||
|
||||
@@ -81,8 +123,12 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
showToast("Bitte einen Namen angeben.", "error");
|
||||
return;
|
||||
}
|
||||
const config =
|
||||
mode === "snapshot"
|
||||
? { mode, measure: props.measure, group: props.group, split: props.split, asOf: props.asOf, ...props.filters }
|
||||
: { mode, group: props.eventGroup, split: props.eventSplit, eventType: props.eventType, ...props.eventFilters };
|
||||
setSavingReport(true);
|
||||
const result = await saveReport({ name: newReportName.trim(), config: { measure, group, split, ...filters } });
|
||||
const result = await saveReport({ name: newReportName.trim(), config });
|
||||
setSavingReport(false);
|
||||
if (result.success) {
|
||||
showToast("Bericht gespeichert.");
|
||||
@@ -104,36 +150,85 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
}
|
||||
}
|
||||
|
||||
function handleExportCsv() {
|
||||
const header = [GROUP_LABELS[group], MEASURE_LABELS[measure], "Anzahl", "Anteil (%)"];
|
||||
const lines = [header.join(";")];
|
||||
for (const row of rows) {
|
||||
const share = total > 0 ? ((row.value / total) * 100).toFixed(1) : "0";
|
||||
lines.push([row.key, formatValue(measure, row.value), String(row.count), share].join(";"));
|
||||
function reportExportHref(format: "csv" | "xlsx"): string {
|
||||
const sp = new URLSearchParams();
|
||||
sp.set("format", format);
|
||||
sp.set("mode", mode);
|
||||
if (mode === "snapshot") {
|
||||
sp.set("measure", props.measure);
|
||||
sp.set("group", props.group);
|
||||
if (props.split) sp.set("split", props.split);
|
||||
if (props.asOf) sp.set("asOf", props.asOf);
|
||||
for (const [k, v] of Object.entries(props.filters)) if (v) sp.set(k, v);
|
||||
} else {
|
||||
sp.set("group", props.eventGroup);
|
||||
if (props.eventSplit) sp.set("split", props.eventSplit);
|
||||
if (props.eventType) sp.set("eventType", props.eventType);
|
||||
for (const [k, v] of Object.entries(props.eventFilters)) if (v) sp.set(k, v);
|
||||
}
|
||||
const blob = new Blob([lines.join("\n")], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `bericht-${measure}-${group}.csv`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
return `/api/export/report?${sp.toString()}`;
|
||||
}
|
||||
|
||||
const isAverage = AVERAGE_MEASURES.includes(measure);
|
||||
const isDateScoped = DATE_SCOPED_MEASURES.includes(measure);
|
||||
function fullExportHref(format: "csv" | "xlsx"): string {
|
||||
if (mode === "snapshot") {
|
||||
const sp = new URLSearchParams();
|
||||
sp.set("format", format);
|
||||
if (props.asOf) sp.set("asOf", props.asOf);
|
||||
if (props.filters.division) sp.set("division", props.filters.division);
|
||||
if (props.filters.location) sp.set("location", props.filters.location);
|
||||
if (props.filters.status) sp.set("status", props.filters.status);
|
||||
if (props.filters.employment) sp.set("employment", props.filters.employment);
|
||||
return `/api/export/employees?${sp.toString()}`;
|
||||
}
|
||||
const sp = new URLSearchParams();
|
||||
sp.set("format", format);
|
||||
if (props.eventType) sp.set("eventType", props.eventType);
|
||||
for (const [k, v] of Object.entries(props.eventFilters)) if (v) sp.set(k, v);
|
||||
return `/api/export/events?${sp.toString()}`;
|
||||
}
|
||||
|
||||
const isAverage = mode === "snapshot" && AVERAGE_MEASURES.includes(props.measure);
|
||||
const maxValue = Math.max(1, ...rows.map((r) => r.value));
|
||||
const selectedStatuses = mode === "snapshot" ? parseStatuses(props.filters.status) : [];
|
||||
const statusExportLabel = selectedStatuses.length === STATUS_OPTIONS.length ? "Alle" : selectedStatuses.join(", ");
|
||||
const currentYear = new Date().getFullYear();
|
||||
const defaultEventFrom = `${currentYear}-01-01`;
|
||||
const defaultEventTo = `${currentYear}-12-31`;
|
||||
|
||||
const heading =
|
||||
mode === "snapshot"
|
||||
? `${MEASURE_LABELS[props.measure]} nach ${GROUP_LABELS[props.group]}`
|
||||
: `${props.eventType ? EVENT_TYPE_LABELS[props.eventType as HistoryEventType] : "Ereignisse"} nach ${EVENT_GROUP_LABELS[props.eventGroup]}`;
|
||||
const totalDisplay = mode === "snapshot" ? formatValue(props.measure, total) : String(Math.round(total));
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-[320px_1fr]">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex rounded border border-border bg-white p-1 text-sm font-semibold">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode("snapshot")}
|
||||
className={`flex-1 rounded px-3 py-1.5 ${mode === "snapshot" ? "bg-brand-500 text-white" : "text-ink-body hover:bg-surface"}`}
|
||||
>
|
||||
Bestand
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => switchMode("events")}
|
||||
className={`flex-1 rounded px-3 py-1.5 ${mode === "events" ? "bg-brand-500 text-white" : "text-ink-body hover:bg-surface"}`}
|
||||
>
|
||||
Ereignisse
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{mode === "snapshot" ? (
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Kennzahl</label>
|
||||
<select
|
||||
value={measure}
|
||||
onChange={(e) => updateParams({ measure: e.target.value, split: AVERAGE_MEASURES.includes(e.target.value as Measure) ? undefined : split })}
|
||||
value={props.measure}
|
||||
onChange={(e) => updateParams({ measure: e.target.value, split: AVERAGE_MEASURES.includes(e.target.value as Measure) ? undefined : props.split })}
|
||||
className="w-full rounded border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
{(Object.keys(MEASURE_LABELS) as Measure[]).map((m) => (
|
||||
@@ -145,7 +240,7 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Gruppieren nach</label>
|
||||
<select value={group} onChange={(e) => updateParams({ group: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
<select value={props.group} onChange={(e) => updateParams({ group: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
{(Object.keys(GROUP_LABELS) as GroupDimension[]).map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{GROUP_LABELS[g]}
|
||||
@@ -156,14 +251,14 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Aufteilen nach</label>
|
||||
<select
|
||||
value={split}
|
||||
value={props.split}
|
||||
disabled={isAverage}
|
||||
onChange={(e) => updateParams({ split: e.target.value || undefined })}
|
||||
className="w-full rounded border border-border px-3 py-2 text-sm disabled:bg-surface disabled:text-ink-muted"
|
||||
>
|
||||
<option value="">Keine Aufteilung</option>
|
||||
{(Object.keys(GROUP_LABELS) as GroupDimension[])
|
||||
.filter((g) => g !== group)
|
||||
.filter((g) => g !== props.group)
|
||||
.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{GROUP_LABELS[g]}
|
||||
@@ -171,13 +266,113 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Stichtag</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="date"
|
||||
value={props.asOf || todayIso()}
|
||||
onChange={(e) => updateParams({ asOf: e.target.value })}
|
||||
className="w-full rounded border border-border px-3 py-2 text-sm"
|
||||
/>
|
||||
{props.asOf && (
|
||||
<button type="button" onClick={() => updateParams({ asOf: undefined })} className="whitespace-nowrap text-xs font-semibold text-brand-700 hover:underline">
|
||||
Heute
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="mt-1 text-xs text-ink-muted">
|
||||
Bestand wird rückgerechnet (Eintritt/Austritt/Karenz); Bereich/Team zeigen die aktuelle Zuordnung.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Ereignistyp</label>
|
||||
<select value={props.eventType} onChange={(e) => updateParams({ eventType: e.target.value || undefined })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
<option value="">Alle Ereignistypen</option>
|
||||
{EVENT_TYPES.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{EVENT_TYPE_LABELS[t]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Gruppieren nach</label>
|
||||
<select value={props.eventGroup} onChange={(e) => updateParams({ group: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
{(Object.keys(EVENT_GROUP_LABELS) as EventGroupDimension[]).map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{EVENT_GROUP_LABELS[g]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Aufteilen nach</label>
|
||||
<select value={props.eventSplit} onChange={(e) => updateParams({ split: e.target.value || undefined })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
<option value="">Keine Aufteilung</option>
|
||||
{(Object.keys(EVENT_GROUP_LABELS) as EventGroupDimension[])
|
||||
.filter((g) => g !== props.eventGroup)
|
||||
.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{EVENT_GROUP_LABELS[g]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-xs font-semibold uppercase tracking-wide text-ink-muted">Zeitraum</label>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<input
|
||||
type="date"
|
||||
value={props.eventFilters.from === EVENT_DATE_OPEN ? "" : props.eventFilters.from || defaultEventFrom}
|
||||
disabled={props.eventFilters.from === EVENT_DATE_OPEN}
|
||||
onChange={(e) => updateParams({ from: e.target.value })}
|
||||
className="w-full rounded border border-border px-2 py-2 text-xs disabled:bg-surface"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateParams({ from: props.eventFilters.from === EVENT_DATE_OPEN ? defaultEventFrom : EVENT_DATE_OPEN })}
|
||||
className="mt-1 text-xs font-semibold text-brand-700 hover:underline"
|
||||
>
|
||||
{props.eventFilters.from === EVENT_DATE_OPEN ? "Startdatum setzen" : "Ab Anfang (offen)"}
|
||||
</button>
|
||||
</div>
|
||||
<div>
|
||||
<input
|
||||
type="date"
|
||||
value={props.eventFilters.to === EVENT_DATE_OPEN ? "" : props.eventFilters.to || defaultEventTo}
|
||||
disabled={props.eventFilters.to === EVENT_DATE_OPEN}
|
||||
onChange={(e) => updateParams({ to: e.target.value })}
|
||||
className="w-full rounded border border-border px-2 py-2 text-xs disabled:bg-surface"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => updateParams({ to: props.eventFilters.to === EVENT_DATE_OPEN ? defaultEventTo : EVENT_DATE_OPEN })}
|
||||
className="mt-1 text-xs font-semibold text-brand-700 hover:underline"
|
||||
>
|
||||
{props.eventFilters.to === EVENT_DATE_OPEN ? "Enddatum setzen" : "Bis heute (offen)"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">Filter</h3>
|
||||
<div className="flex flex-col gap-2">
|
||||
<select value={filters.division} onChange={(e) => updateParams({ division: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
<select
|
||||
value={mode === "snapshot" ? props.filters.division : props.eventFilters.division}
|
||||
onChange={(e) => updateParams({ division: e.target.value })}
|
||||
className="w-full rounded border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">Alle Bereiche</option>
|
||||
{divisions.map((d) => (
|
||||
<option key={d.id} value={d.id}>
|
||||
@@ -185,7 +380,11 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select value={filters.location} onChange={(e) => updateParams({ location: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
<select
|
||||
value={mode === "snapshot" ? props.filters.location : props.eventFilters.location}
|
||||
onChange={(e) => updateParams({ location: e.target.value })}
|
||||
className="w-full rounded border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
<option value="">Alle Standorte</option>
|
||||
{locations.map((l) => (
|
||||
<option key={l.id} value={l.id}>
|
||||
@@ -193,15 +392,26 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select value={filters.status} onChange={(e) => updateParams({ status: e.target.value })} className="w-full rounded border border-border px-3 py-2 text-sm">
|
||||
<option value="">Alle Status</option>
|
||||
<option value="Aktiv">Aktiv</option>
|
||||
<option value="Karenz">Karenz</option>
|
||||
<option value="Geplant">Geplant</option>
|
||||
<option value="Ausgetreten">Ausgetreten</option>
|
||||
</select>
|
||||
{mode === "snapshot" && (
|
||||
<>
|
||||
<div className="rounded border border-border px-3 py-2">
|
||||
<p className="mb-1.5 text-xs font-semibold text-ink-muted">Status (zum Stichtag)</p>
|
||||
<div className="flex flex-wrap gap-x-4 gap-y-1.5">
|
||||
{STATUS_OPTIONS.map((s) => (
|
||||
<label key={s} className="flex items-center gap-1.5 text-sm text-ink-body">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={selectedStatuses.includes(s)}
|
||||
onChange={() => toggleStatus(s)}
|
||||
className="h-4 w-4 rounded border-border accent-brand-500"
|
||||
/>
|
||||
{s}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<select
|
||||
value={filters.employment}
|
||||
value={props.filters.employment}
|
||||
onChange={(e) => updateParams({ employment: e.target.value })}
|
||||
className="w-full rounded border border-border px-3 py-2 text-sm"
|
||||
>
|
||||
@@ -209,21 +419,7 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
<option value="Vollzeit">Vollzeit</option>
|
||||
<option value="Teilzeit">Teilzeit</option>
|
||||
</select>
|
||||
{isDateScoped && (
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<input
|
||||
type="date"
|
||||
value={filters.from}
|
||||
onChange={(e) => updateParams({ from: e.target.value })}
|
||||
className="w-full rounded border border-border px-2 py-2 text-xs"
|
||||
/>
|
||||
<input
|
||||
type="date"
|
||||
value={filters.to}
|
||||
onChange={(e) => updateParams({ to: e.target.value })}
|
||||
className="w-full rounded border border-border px-2 py-2 text-xs"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -231,7 +427,7 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">Vorlagen</h3>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{REPORT_PRESETS.map((preset) => (
|
||||
{(mode === "snapshot" ? REPORT_PRESETS : EVENT_REPORT_PRESETS).map((preset) => (
|
||||
<button
|
||||
key={preset.name}
|
||||
type="button"
|
||||
@@ -244,6 +440,28 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<h3 className="mb-1 text-xs font-semibold uppercase tracking-wide text-ink-muted">Vollständiger Datenexport</h3>
|
||||
{mode === "snapshot" ? (
|
||||
<>
|
||||
<p className="mb-1 text-xs text-ink-muted">Alle Mitarbeiterdaten (nicht nur die Kennzahl){props.asOf ? ` zum Stichtag ${fmtDate(props.asOf)}` : ""}.</p>
|
||||
<p className="mb-2 rounded bg-surface px-2 py-1.5 text-xs font-semibold text-ink-body">Status im Export: {statusExportLabel}</p>
|
||||
</>
|
||||
) : (
|
||||
<p className="mb-2 text-xs text-ink-muted">Alle Ereignisse im gewählten Zeitraum als Rohdaten (eine Zeile pro Ereignis).</p>
|
||||
)}
|
||||
<div className="flex gap-2">
|
||||
<a href={fullExportHref("csv")} className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface">
|
||||
<FileText className="h-4 w-4" />
|
||||
CSV
|
||||
</a>
|
||||
<a href={fullExportHref("xlsx")} className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
Excel
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{savedReports.length > 0 && (
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<h3 className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">Gespeicherte Berichte</h3>
|
||||
@@ -266,20 +484,18 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
<div className="rounded border border-border bg-white p-4">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||
<div>
|
||||
<h2 className="text-base font-bold text-ink">
|
||||
{MEASURE_LABELS[measure]} nach {GROUP_LABELS[group]}
|
||||
</h2>
|
||||
<p className="text-xs text-ink-muted">{recordCount} Datensätze</p>
|
||||
<h2 className="text-base font-bold text-ink">{heading}</h2>
|
||||
<p className="text-xs text-ink-muted">{recordCount} {mode === "snapshot" ? "Datensätze" : "Ereignisse"}</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleExportCsv}
|
||||
className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface"
|
||||
>
|
||||
<Download className="h-4 w-4" />
|
||||
CSV exportieren
|
||||
</button>
|
||||
<a href={reportExportHref("csv")} className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface">
|
||||
<FileText className="h-4 w-4" />
|
||||
CSV
|
||||
</a>
|
||||
<a href={reportExportHref("xlsx")} className="flex items-center gap-1.5 rounded border border-border px-3 py-1.5 text-sm font-semibold text-ink-body hover:bg-surface">
|
||||
<FileSpreadsheet className="h-4 w-4" />
|
||||
Excel
|
||||
</a>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setSaveModalOpen(true)}
|
||||
@@ -291,9 +507,9 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="mb-4 text-2xl font-extrabold text-ink">{formatValue(measure, total)}</p>
|
||||
<p className="mb-4 text-2xl font-extrabold text-ink">{totalDisplay}</p>
|
||||
|
||||
{split && (
|
||||
{((mode === "snapshot" && props.split) || (mode === "events" && props.eventSplit)) && (
|
||||
<div className="mb-3 flex flex-wrap gap-3">
|
||||
{Array.from(new Set(rows.flatMap((r) => r.split?.map((s) => s.key) ?? []))).map((key, i) => (
|
||||
<span key={key} className="flex items-center gap-1.5 text-xs text-ink-body">
|
||||
@@ -310,25 +526,18 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
const isExpanded = expandedKey === row.key;
|
||||
return (
|
||||
<div key={row.key}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedKey(isExpanded ? null : row.key)}
|
||||
className="w-full text-left"
|
||||
>
|
||||
<button type="button" onClick={() => setExpandedKey(isExpanded ? null : row.key)} className="w-full text-left">
|
||||
<div className="mb-1 flex items-center justify-between text-sm">
|
||||
<span className="font-semibold text-ink">{row.key}</span>
|
||||
<span className="text-ink-body">
|
||||
{formatValue(measure, row.value)} <span className="text-xs text-ink-muted">({share.toFixed(1)}%)</span>
|
||||
{mode === "snapshot" ? formatValue(props.measure, row.value) : Math.round(row.value)}{" "}
|
||||
<span className="text-xs text-ink-muted">({share.toFixed(1)}%)</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex h-2.5 overflow-hidden rounded bg-surface">
|
||||
{row.split ? (
|
||||
row.split.map((s, i) => (
|
||||
<div
|
||||
key={s.key}
|
||||
className={SPLIT_COLORS[i % SPLIT_COLORS.length]}
|
||||
style={{ width: `${maxValue > 0 ? (s.value / maxValue) * 100 : 0}%` }}
|
||||
/>
|
||||
<div key={s.key} className={SPLIT_COLORS[i % SPLIT_COLORS.length]} style={{ width: `${maxValue > 0 ? (s.value / maxValue) * 100 : 0}%` }} />
|
||||
))
|
||||
) : (
|
||||
<div className="bg-brand-500" style={{ width: `${(row.value / maxValue) * 100}%` }} />
|
||||
@@ -338,8 +547,8 @@ export function ReportsPageClient(props: ReportsPageClientProps) {
|
||||
{isExpanded && (
|
||||
<div className="mt-2 rounded border border-border bg-surface p-3">
|
||||
<ul className="flex flex-col divide-y divide-border">
|
||||
{row.people.slice(0, 12).map((p) => (
|
||||
<li key={p.id} className="flex items-center justify-between py-1.5 text-sm">
|
||||
{row.people.slice(0, 12).map((p, i) => (
|
||||
<li key={`${p.id}-${i}`} className="flex items-center justify-between py-1.5 text-sm">
|
||||
<Link href={`/employees/${p.id}`} className="font-semibold text-ink hover:text-brand-700 hover:underline">
|
||||
{p.name}
|
||||
</Link>
|
||||
|
||||
90
lib/export.ts
Normal file
90
lib/export.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
import ExcelJS from "exceljs";
|
||||
|
||||
// Shared by every /api/export/* route: define columns once as { header, get },
|
||||
// get both a semicolon CSV (Excel-DE friendly) and a real .xlsx workbook from
|
||||
// the same data + column definitions. kind: "date" tells the xlsx writer to
|
||||
// emit a real date cell (not a text string) for ISO ("YYYY-MM-DD") values.
|
||||
export type ExportColumn<T> = {
|
||||
header: string;
|
||||
get: (row: T) => string | number | boolean | null;
|
||||
kind?: "date";
|
||||
};
|
||||
|
||||
// CSV/Excel formula injection (CWE-1236): a cell whose text begins with
|
||||
// =, +, -, or @ is interpreted as a formula by Excel/Sheets/LibreOffice on
|
||||
// open, not as literal text — dangerous when the source data (employee
|
||||
// names, job titles, free-text notes, audit details, ...) can contain
|
||||
// attacker- or user-supplied strings. Prefixing with a single quote is the
|
||||
// standard mitigation (OWASP CSV Injection cheat sheet); it forces the cell
|
||||
// to render as text at the cost of a visible leading ' for the rare
|
||||
// legitimate value that starts with one of these characters.
|
||||
export function sanitizeForSpreadsheetCell(text: string): string {
|
||||
return /^[=+\-@]/.test(text) ? `'${text}` : text;
|
||||
}
|
||||
|
||||
function csvCell(value: string | number | boolean | null): string {
|
||||
if (value === null || value === undefined) return "";
|
||||
const text = typeof value === "boolean" ? (value ? "Ja" : "Nein") : sanitizeForSpreadsheetCell(String(value));
|
||||
return /[";\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
||||
}
|
||||
|
||||
// Leading BOM + semicolon delimiter: Excel's German locale default, and what
|
||||
// makes umlauts render correctly instead of mojibake on open.
|
||||
export function toCsv<T>(rows: T[], columns: ExportColumn<T>[]): string {
|
||||
const lines = [columns.map((c) => csvCell(c.header)).join(";")];
|
||||
for (const row of rows) {
|
||||
lines.push(columns.map((c) => csvCell(c.get(row))).join(";"));
|
||||
}
|
||||
return "" + lines.join("\r\n");
|
||||
}
|
||||
|
||||
function parseIsoDate(value: string): Date | null {
|
||||
const d = new Date(`${value}T00:00:00`);
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
export async function toXlsx<T>(rows: T[], columns: ExportColumn<T>[], sheetName: string): Promise<Uint8Array> {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const sheet = workbook.addWorksheet(sheetName.slice(0, 31));
|
||||
|
||||
sheet.columns = columns.map((c) => ({
|
||||
header: c.header,
|
||||
key: c.header,
|
||||
width: Math.min(40, Math.max(12, c.header.length + 4)),
|
||||
style: c.kind === "date" ? { numFmt: "dd.mm.yyyy" } : undefined,
|
||||
}));
|
||||
sheet.getRow(1).font = { bold: true };
|
||||
sheet.autoFilter = { from: { row: 1, column: 1 }, to: { row: 1, column: columns.length } };
|
||||
sheet.views = [{ state: "frozen", ySplit: 1 }];
|
||||
|
||||
for (const row of rows) {
|
||||
const record: Record<string, string | number | boolean | Date | null> = {};
|
||||
for (const c of columns) {
|
||||
const value = c.get(row);
|
||||
record[c.header] =
|
||||
c.kind === "date" && typeof value === "string" && value
|
||||
? (parseIsoDate(value) ?? value)
|
||||
: typeof value === "string"
|
||||
? sanitizeForSpreadsheetCell(value)
|
||||
: value;
|
||||
}
|
||||
sheet.addRow(record);
|
||||
}
|
||||
|
||||
const written = await workbook.xlsx.writeBuffer();
|
||||
return new Uint8Array(written);
|
||||
}
|
||||
|
||||
export function exportFilename(base: string, format: "csv" | "xlsx"): string {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
return `${base}-${today}.${format}`;
|
||||
}
|
||||
|
||||
export function exportResponseHeaders(filename: string, format: "csv" | "xlsx"): HeadersInit {
|
||||
const contentType =
|
||||
format === "xlsx" ? "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" : "text/csv; charset=utf-8";
|
||||
return {
|
||||
"Content-Type": contentType,
|
||||
"Content-Disposition": `attachment; filename="${filename}"`,
|
||||
};
|
||||
}
|
||||
127
lib/reports-data.ts
Normal file
127
lib/reports-data.ts
Normal file
@@ -0,0 +1,127 @@
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import { deriveStatusAsOf, EVENT_DATE_OPEN, parseStatuses, todayIso, type OrgLookups, type ReportEmployee, type ReportEvent } from "./reports";
|
||||
import type { Database, EmploymentType, HistoryEventType } from "./supabase/types";
|
||||
|
||||
// Shared by the Berichte page and /api/export/* so they can never drift on
|
||||
// what "the current view" means — same filters, same stichtag/event-window
|
||||
// rules.
|
||||
export type ReportFilters = {
|
||||
division?: string;
|
||||
location?: string;
|
||||
status?: string;
|
||||
employment?: string;
|
||||
};
|
||||
|
||||
export type SnapshotFilters = ReportFilters & { asOf?: string };
|
||||
export type EventFilters = { eventType?: HistoryEventType; division?: string; location?: string; from?: string; to?: string };
|
||||
|
||||
export async function loadOrgLookups(supabase: SupabaseClient<Database>): Promise<{
|
||||
lookups: OrgLookups;
|
||||
divisions: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
}> {
|
||||
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]));
|
||||
return {
|
||||
lookups: {
|
||||
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])),
|
||||
},
|
||||
divisions: divisions ?? [],
|
||||
locations: locations ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
const SNAPSHOT_EMPLOYEE_COLUMNS =
|
||||
"id, first_name, last_name, job_title, division_id, team_id, location_id, employment_type, contract_type, entry_date, exit_date, weekly_hours, source, paygrade, birth_date, gender, karenz_start_date, karenz_return_date";
|
||||
|
||||
// Bestand zum Stichtag: reconstructs each employee's status as of `asOf`
|
||||
// (defaults to today) from entry/exit/Karenz dates — see deriveStatusAsOf.
|
||||
// division/team/location still reflect the employee's *current* assignment.
|
||||
export async function loadSnapshotEmployees(supabase: SupabaseClient<Database>, filters: SnapshotFilters): Promise<ReportEmployee[]> {
|
||||
const asOf = filters.asOf || todayIso();
|
||||
|
||||
let query = supabase.from("employees").select(SNAPSHOT_EMPLOYEE_COLUMNS);
|
||||
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);
|
||||
|
||||
const { data } = await query;
|
||||
|
||||
const withDerivedStatus: ReportEmployee[] = (data ?? []).map((e) => ({
|
||||
id: e.id,
|
||||
first_name: e.first_name,
|
||||
last_name: e.last_name,
|
||||
job_title: e.job_title,
|
||||
division_id: e.division_id,
|
||||
team_id: e.team_id,
|
||||
location_id: e.location_id,
|
||||
status: deriveStatusAsOf(e, asOf),
|
||||
employment_type: e.employment_type,
|
||||
contract_type: e.contract_type,
|
||||
entry_date: e.entry_date,
|
||||
exit_date: e.exit_date,
|
||||
weekly_hours: e.weekly_hours,
|
||||
source: e.source,
|
||||
paygrade: e.paygrade,
|
||||
birth_date: e.birth_date,
|
||||
gender: e.gender,
|
||||
}));
|
||||
|
||||
const statuses = parseStatuses(filters.status);
|
||||
return withDerivedStatus.filter((e) => statuses.includes(e.status as (typeof statuses)[number]));
|
||||
}
|
||||
|
||||
// Ereignisse: employee_history has no division_id/team_id of its own, so
|
||||
// this joins in the affected employee's *current* org placement (two plain
|
||||
// queries, merged in JS — the hand-written Database type has no relational
|
||||
// embedding metadata for a single nested-select query).
|
||||
//
|
||||
// from/to: "" (unset) falls back to the current calendar year; the literal
|
||||
// sentinel EVENT_DATE_OPEN means that side of the interval is intentionally
|
||||
// unbounded (e.g. "alle Ereignisse bis heute", no start date).
|
||||
export async function loadEventHistory(supabase: SupabaseClient<Database>, filters: EventFilters): Promise<ReportEvent[]> {
|
||||
const currentYear = new Date().getFullYear();
|
||||
const from = filters.from === EVENT_DATE_OPEN ? undefined : filters.from || `${currentYear}-01-01`;
|
||||
const to = filters.to === EVENT_DATE_OPEN ? undefined : filters.to || `${currentYear}-12-31`;
|
||||
|
||||
let historyQuery = supabase.from("employee_history").select("employee_id, event_date, event_type, description");
|
||||
if (from) historyQuery = historyQuery.gte("event_date", from);
|
||||
if (to) historyQuery = historyQuery.lte("event_date", to);
|
||||
if (filters.eventType) historyQuery = historyQuery.eq("event_type", filters.eventType);
|
||||
|
||||
const [{ data: history }, { data: employees }] = await Promise.all([
|
||||
historyQuery,
|
||||
supabase.from("employees").select("id, first_name, last_name, job_title, division_id, team_id, location_id"),
|
||||
]);
|
||||
|
||||
const employeeById = new Map((employees ?? []).map((e) => [e.id, e]));
|
||||
const events: ReportEvent[] = [];
|
||||
for (const h of history ?? []) {
|
||||
const emp = employeeById.get(h.employee_id);
|
||||
if (!emp) continue;
|
||||
if (filters.division && emp.division_id !== filters.division) continue;
|
||||
if (filters.location && emp.location_id !== filters.location) continue;
|
||||
events.push({
|
||||
employee_id: emp.id,
|
||||
first_name: emp.first_name,
|
||||
last_name: emp.last_name,
|
||||
job_title: emp.job_title,
|
||||
division_id: emp.division_id,
|
||||
team_id: emp.team_id,
|
||||
location_id: emp.location_id,
|
||||
event_date: h.event_date,
|
||||
event_type: h.event_type,
|
||||
description: h.description,
|
||||
});
|
||||
}
|
||||
return events;
|
||||
}
|
||||
211
lib/reports.ts
211
lib/reports.ts
@@ -1,12 +1,8 @@
|
||||
export type Measure =
|
||||
| "headcount"
|
||||
| "fte"
|
||||
| "hires"
|
||||
| "exits"
|
||||
| "parttime_rate"
|
||||
| "avg_age"
|
||||
| "avg_tenure"
|
||||
| "female_share";
|
||||
import type { EmploymentStatus, HistoryEventType } from "./supabase/types";
|
||||
|
||||
// ── Bestand (point-in-time snapshot) ──────────────────────────────
|
||||
|
||||
export type Measure = "headcount" | "fte" | "parttime_rate" | "avg_age" | "avg_tenure" | "female_share";
|
||||
|
||||
export type GroupDimension =
|
||||
| "division"
|
||||
@@ -23,8 +19,6 @@ export type GroupDimension =
|
||||
export const MEASURE_LABELS: Record<Measure, string> = {
|
||||
headcount: "Headcount",
|
||||
fte: "FTE",
|
||||
hires: "Eintritte",
|
||||
exits: "Austritte",
|
||||
parttime_rate: "Teilzeitquote",
|
||||
avg_age: "Ø Alter",
|
||||
avg_tenure: "Ø Zugehörigkeit",
|
||||
@@ -45,7 +39,22 @@ export const GROUP_LABELS: Record<GroupDimension, string> = {
|
||||
};
|
||||
|
||||
export const AVERAGE_MEASURES: Measure[] = ["parttime_rate", "avg_age", "avg_tenure", "female_share"];
|
||||
export const DATE_SCOPED_MEASURES: Measure[] = ["hires", "exits"];
|
||||
const SUM_MEASURES: Measure[] = ["headcount", "fte"];
|
||||
|
||||
export const STATUS_OPTIONS: EmploymentStatus[] = ["Aktiv", "Karenz", "Geplant", "Ausgetreten"];
|
||||
export const DEFAULT_STATUSES: EmploymentStatus[] = ["Aktiv", "Karenz"];
|
||||
|
||||
// `status` filters travel through the URL/exports as a comma-joined list
|
||||
// (e.g. "Aktiv,Karenz"); this is the one place that turns that string back
|
||||
// into a validated status set, defaulting to Aktiv+Karenz when unset — used
|
||||
// by both the Bestand pivot and the full data export so they can never
|
||||
// silently disagree on which statuses "no filter" means.
|
||||
export function parseStatuses(status: string | undefined): EmploymentStatus[] {
|
||||
if (!status) return DEFAULT_STATUSES;
|
||||
const requested = status.split(",");
|
||||
const valid = STATUS_OPTIONS.filter((s) => requested.includes(s));
|
||||
return valid.length > 0 ? valid : DEFAULT_STATUSES;
|
||||
}
|
||||
|
||||
export type ReportEmployee = {
|
||||
id: string;
|
||||
@@ -74,17 +83,38 @@ export type OrgLookups = {
|
||||
locationName: Map<string, string>;
|
||||
};
|
||||
|
||||
function ageFromBirthDate(birthDate: string): number {
|
||||
export function todayIso(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
// Reconstructs status as of any date from the columns that actually carry a
|
||||
// timeline (entry/exit/Karenz), rather than trusting `employees.status`,
|
||||
// which only ever reflects *today*. Division/team/location still reflect the
|
||||
// employee's *current* assignment — the schema has no history of org-unit
|
||||
// changes over time, only free-text employee_history descriptions — so a
|
||||
// stichtag report groups by today's org placement, not the placement as of
|
||||
// that date. Documented in the UI rather than silently wrong.
|
||||
export function deriveStatusAsOf(
|
||||
e: { entry_date: string; exit_date: string | null; karenz_start_date: string | null; karenz_return_date: string | null },
|
||||
asOf: string
|
||||
): EmploymentStatus {
|
||||
if (e.entry_date > asOf) return "Geplant";
|
||||
if (e.exit_date && e.exit_date <= asOf) return "Ausgetreten";
|
||||
if (e.karenz_start_date && e.karenz_start_date <= asOf && (!e.karenz_return_date || asOf < e.karenz_return_date)) return "Karenz";
|
||||
return "Aktiv";
|
||||
}
|
||||
|
||||
function ageAsOf(birthDate: string, asOf: string): number {
|
||||
const d = new Date(birthDate);
|
||||
const today = new Date();
|
||||
let age = today.getFullYear() - d.getFullYear();
|
||||
if (today.getMonth() < d.getMonth() || (today.getMonth() === d.getMonth() && today.getDate() < d.getDate())) age -= 1;
|
||||
const ref = new Date(asOf);
|
||||
let age = ref.getFullYear() - d.getFullYear();
|
||||
if (ref.getMonth() < d.getMonth() || (ref.getMonth() === d.getMonth() && ref.getDate() < d.getDate())) age -= 1;
|
||||
return age;
|
||||
}
|
||||
|
||||
function tenureYears(entryDate: string, exitDate: string | null): number {
|
||||
function tenureYearsAsOf(entryDate: string, exitDate: string | null, asOf: string): number {
|
||||
const start = new Date(entryDate);
|
||||
const end = exitDate ? new Date(exitDate) : new Date();
|
||||
const end = exitDate && exitDate <= asOf ? new Date(exitDate) : new Date(asOf);
|
||||
return Math.max(0, (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24 * 365.25));
|
||||
}
|
||||
|
||||
@@ -115,21 +145,19 @@ export function groupKeyFor(e: ReportEmployee, dim: GroupDimension, lookups: Org
|
||||
}
|
||||
}
|
||||
|
||||
export function measureValue(rows: ReportEmployee[], measure: Measure): number {
|
||||
export function measureValue(rows: ReportEmployee[], measure: Measure, asOf: string = todayIso()): number {
|
||||
if (rows.length === 0) return 0;
|
||||
switch (measure) {
|
||||
case "headcount":
|
||||
case "hires":
|
||||
case "exits":
|
||||
return rows.length;
|
||||
case "fte":
|
||||
return rows.reduce((s, e) => s + e.weekly_hours / 38.5, 0);
|
||||
case "parttime_rate":
|
||||
return (rows.filter((e) => e.employment_type === "Teilzeit").length / rows.length) * 100;
|
||||
case "avg_age":
|
||||
return rows.reduce((s, e) => s + ageFromBirthDate(e.birth_date), 0) / rows.length;
|
||||
return rows.reduce((s, e) => s + ageAsOf(e.birth_date, asOf), 0) / rows.length;
|
||||
case "avg_tenure":
|
||||
return rows.reduce((s, e) => s + tenureYears(e.entry_date, e.exit_date), 0) / rows.length;
|
||||
return rows.reduce((s, e) => s + tenureYearsAsOf(e.entry_date, e.exit_date, asOf), 0) / rows.length;
|
||||
case "female_share":
|
||||
return (rows.filter((e) => e.gender === "w").length / rows.length) * 100;
|
||||
default:
|
||||
@@ -146,7 +174,8 @@ export function aggregateReport(
|
||||
measure: Measure,
|
||||
group: GroupDimension,
|
||||
split: GroupDimension | null,
|
||||
lookups: OrgLookups
|
||||
lookups: OrgLookups,
|
||||
asOf: string = todayIso()
|
||||
): ReportRow[] {
|
||||
const byGroup = new Map<string, ReportEmployee[]>();
|
||||
for (const e of employees) {
|
||||
@@ -157,7 +186,7 @@ export function aggregateReport(
|
||||
|
||||
const rows: ReportRow[] = [];
|
||||
for (const [key, rowsForGroup] of byGroup) {
|
||||
const value = measureValue(rowsForGroup, measure);
|
||||
const value = measureValue(rowsForGroup, measure, asOf);
|
||||
const people: ReportPerson[] = rowsForGroup.map((e) => ({
|
||||
id: e.id,
|
||||
name: `${e.first_name} ${e.last_name}`,
|
||||
@@ -175,7 +204,7 @@ export function aggregateReport(
|
||||
}
|
||||
row.split = Array.from(bySplit.entries()).map(([sKey, sRows]) => ({
|
||||
key: sKey,
|
||||
value: measureValue(sRows, measure),
|
||||
value: measureValue(sRows, measure, asOf),
|
||||
count: sRows.length,
|
||||
}));
|
||||
}
|
||||
@@ -184,11 +213,137 @@ export function aggregateReport(
|
||||
return rows.sort((a, b) => b.value - a.value);
|
||||
}
|
||||
|
||||
export function sumValues(rows: { value: number }[]): number {
|
||||
return rows.reduce((s, r) => s + r.value, 0);
|
||||
}
|
||||
|
||||
// headcount/fte sum across groups; averages/ratios are weighted by each
|
||||
// group's underlying record count for a sensible overall figure.
|
||||
export function totalForRows(rows: { value: number; count: number }[], measure: Measure): number {
|
||||
if (SUM_MEASURES.includes(measure)) return sumValues(rows);
|
||||
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;
|
||||
}
|
||||
|
||||
export const REPORT_PRESETS: { name: string; measure: Measure; group: GroupDimension; split?: GroupDimension }[] = [
|
||||
{ name: "Headcount nach Bereich", measure: "headcount", group: "division" },
|
||||
{ name: "Frauenanteil nach Bereich", measure: "female_share", group: "division" },
|
||||
{ name: "Headcount nach Paygrade", measure: "headcount", group: "paygrade" },
|
||||
{ name: "Teilzeitquote nach Standort", measure: "parttime_rate", group: "location" },
|
||||
{ name: "Eintritte nach Bereich", measure: "hires", group: "division" },
|
||||
{ name: "Austritte nach Abteilung", measure: "exits", group: "department" },
|
||||
];
|
||||
|
||||
// ── Ereignisse (events over a period) ─────────────────────────────
|
||||
// Backed by employee_history, the append-only log — unlike Bestand, this
|
||||
// covers every event type (not just Eintritt/Austritt), survives an
|
||||
// employee's entry_date being overwritten by a later rehire, and each event
|
||||
// keeps its own date/description regardless of the employee's current state.
|
||||
|
||||
// Sentinel for "von"/"bis" — distinct from "" (unset, falls back to the
|
||||
// current-year default) or a real date. Written to the URL/exports as the
|
||||
// literal string "open".
|
||||
export const EVENT_DATE_OPEN = "open";
|
||||
|
||||
export type EventGroupDimension = "event_type" | "division" | "department" | "team" | "location" | "event_year";
|
||||
|
||||
export const EVENT_GROUP_LABELS: Record<EventGroupDimension, string> = {
|
||||
event_type: "Ereignistyp",
|
||||
division: "Bereich",
|
||||
department: "Abteilung",
|
||||
team: "Team",
|
||||
location: "Standort",
|
||||
event_year: "Jahr",
|
||||
};
|
||||
|
||||
export const EVENT_TYPE_LABELS: Record<HistoryEventType, string> = {
|
||||
Eintritt: "Eintritt",
|
||||
Beförderung: "Beförderung",
|
||||
Versetzung: "Versetzung",
|
||||
Karenz: "Karenz",
|
||||
Vertragsänderung: "Vertragsänderung",
|
||||
Stammdatenänderung: "Stammdatenänderung",
|
||||
Austritt: "Austritt",
|
||||
Wiedereintritt: "Wiedereintritt",
|
||||
Reorganisation: "Reorganisation",
|
||||
Gehaltsanpassung: "Gehaltsanpassung",
|
||||
Rückkehr: "Rückkehr (Karenz)",
|
||||
};
|
||||
|
||||
export type ReportEvent = {
|
||||
employee_id: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
job_title: string;
|
||||
division_id: string;
|
||||
team_id: string | null;
|
||||
location_id: string;
|
||||
event_date: string;
|
||||
event_type: HistoryEventType;
|
||||
description: string;
|
||||
};
|
||||
|
||||
function eventGroupKeyFor(e: ReportEvent, dim: EventGroupDimension, lookups: OrgLookups): string {
|
||||
switch (dim) {
|
||||
case "event_type":
|
||||
return EVENT_TYPE_LABELS[e.event_type] ?? e.event_type;
|
||||
case "division":
|
||||
return lookups.divisionName.get(e.division_id) ?? "Unbekannt";
|
||||
case "department":
|
||||
return e.team_id ? (lookups.departmentNameByTeam.get(e.team_id) ?? "Unbekannt") : "–";
|
||||
case "team":
|
||||
return e.team_id ? (lookups.teamName.get(e.team_id) ?? "Unbekannt") : "–";
|
||||
case "location":
|
||||
return lookups.locationName.get(e.location_id) ?? "Unbekannt";
|
||||
case "event_year":
|
||||
return String(new Date(e.event_date).getFullYear());
|
||||
default:
|
||||
return "Unbekannt";
|
||||
}
|
||||
}
|
||||
|
||||
export function aggregateEvents(
|
||||
events: ReportEvent[],
|
||||
group: EventGroupDimension,
|
||||
split: EventGroupDimension | null,
|
||||
lookups: OrgLookups
|
||||
): ReportRow[] {
|
||||
const byGroup = new Map<string, ReportEvent[]>();
|
||||
for (const e of events) {
|
||||
const key = eventGroupKeyFor(e, group, lookups);
|
||||
if (!byGroup.has(key)) byGroup.set(key, []);
|
||||
byGroup.get(key)!.push(e);
|
||||
}
|
||||
|
||||
const rows: ReportRow[] = [];
|
||||
for (const [key, rowsForGroup] of byGroup) {
|
||||
// Repurposes ReportPerson for events: title -> event description,
|
||||
// entry_date -> event_date. Keeps the existing drill-down UI/export
|
||||
// code working unchanged for both report modes.
|
||||
const people: ReportPerson[] = rowsForGroup.map((e) => ({
|
||||
id: e.employee_id,
|
||||
name: `${e.first_name} ${e.last_name}`,
|
||||
title: e.description,
|
||||
team: e.team_id ? (lookups.teamName.get(e.team_id) ?? "–") : "–",
|
||||
entry_date: e.event_date,
|
||||
}));
|
||||
const row: ReportRow = { key, value: rowsForGroup.length, count: rowsForGroup.length, people };
|
||||
if (split) {
|
||||
const bySplit = new Map<string, ReportEvent[]>();
|
||||
for (const e of rowsForGroup) {
|
||||
const sKey = eventGroupKeyFor(e, split, lookups);
|
||||
if (!bySplit.has(sKey)) bySplit.set(sKey, []);
|
||||
bySplit.get(sKey)!.push(e);
|
||||
}
|
||||
row.split = Array.from(bySplit.entries()).map(([sKey, sRows]) => ({ key: sKey, value: sRows.length, count: sRows.length }));
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
return rows.sort((a, b) => b.value - a.value);
|
||||
}
|
||||
|
||||
export const EVENT_REPORT_PRESETS: { name: string; group: EventGroupDimension; split?: EventGroupDimension; eventType?: HistoryEventType }[] = [
|
||||
{ name: "Ereignisse nach Typ", group: "event_type" },
|
||||
{ name: "Eintritte nach Bereich", group: "division", eventType: "Eintritt" },
|
||||
{ name: "Austritte nach Abteilung", group: "department", eventType: "Austritt" },
|
||||
{ name: "Beförderungen nach Bereich", group: "division", eventType: "Beförderung" },
|
||||
];
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import "server-only";
|
||||
import { createClient as createSupabaseClient } from "@supabase/supabase-js";
|
||||
import type { Database } from "./types";
|
||||
|
||||
// Service-role client: bypasses RLS entirely. Server-only — never import this
|
||||
// from a Client Component or anything bundled for the browser.
|
||||
// from a Client Component or anything bundled for the browser. The
|
||||
// "server-only" import makes an accidental client-side import a build error
|
||||
// instead of a runtime one.
|
||||
export function createAdminClient() {
|
||||
if (typeof window !== "undefined") {
|
||||
throw new Error("createAdminClient must never be called in the browser");
|
||||
}
|
||||
|
||||
return createSupabaseClient<Database>(
|
||||
process.env.NEXT_PUBLIC_SUPABASE_URL!,
|
||||
process.env.SUPABASE_SERVICE_ROLE_KEY!,
|
||||
|
||||
9
lib/supabase/query.ts
Normal file
9
lib/supabase/query.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
// PostgREST's .or() filter syntax treats "," "(" and ")" as structural
|
||||
// delimiters between conditions. A raw user-supplied search term containing
|
||||
// them (e.g. from a search box or ?q= param) can break out of the intended
|
||||
// column conditions and append arbitrary extra filters to the query. Strip
|
||||
// them before interpolating — harmless for real name/title searches, which
|
||||
// never legitimately contain them.
|
||||
export function sanitizeIlikeTerm(term: string): string {
|
||||
return term.replace(/[,()]/g, "");
|
||||
}
|
||||
@@ -1,7 +1,25 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
// Baseline security headers (clickjacking, MIME-sniffing, referrer leakage,
|
||||
// browser feature access). No Content-Security-Policy yet: this app has no
|
||||
// inventory of its script/style/connect sources, and shipping a guessed
|
||||
// CSP risks silently breaking Next.js hydration or the Supabase client —
|
||||
// TODO revisit once the actual source list is audited.
|
||||
async headers() {
|
||||
return [
|
||||
{
|
||||
source: "/:path*",
|
||||
headers: [
|
||||
{ key: "X-Frame-Options", value: "SAMEORIGIN" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
{ key: "Referrer-Policy", value: "strict-origin-when-cross-origin" },
|
||||
{ key: "Permissions-Policy", value: "camera=(), microphone=(), geolocation=()" },
|
||||
{ key: "Strict-Transport-Security", value: "max-age=63072000; includeSubDomains" },
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
1045
package-lock.json
generated
1045
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -17,10 +17,12 @@
|
||||
"dependencies": {
|
||||
"@supabase/ssr": "^0.12.1",
|
||||
"@supabase/supabase-js": "^2.110.5",
|
||||
"exceljs": "^4.4.0",
|
||||
"lucide-react": "^1.24.0",
|
||||
"next": "16.2.10",
|
||||
"react": "19.2.7",
|
||||
"react-dom": "19.2.7"
|
||||
"react-dom": "19.2.7",
|
||||
"server-only": "^0.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4.3.2",
|
||||
@@ -35,5 +37,8 @@
|
||||
"tailwindcss": "^4.3.2",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.10"
|
||||
},
|
||||
"overrides": {
|
||||
"postcss": "^8.5.19"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
aggregateEvents,
|
||||
aggregateReport,
|
||||
deriveStatusAsOf,
|
||||
groupKeyFor,
|
||||
measureValue,
|
||||
MEASURE_LABELS,
|
||||
type Measure,
|
||||
type OrgLookups,
|
||||
type ReportEmployee,
|
||||
type ReportEvent,
|
||||
} from "@/lib/reports";
|
||||
|
||||
function emp(overrides: Partial<ReportEmployee> = {}): ReportEmployee {
|
||||
@@ -76,9 +78,9 @@ describe("measureValue", () => {
|
||||
expect(measureValue([], "headcount")).toBe(0);
|
||||
});
|
||||
|
||||
it("counts headcount/hires/exits as row length", () => {
|
||||
it("counts headcount as row length", () => {
|
||||
const rows = [emp(), emp({ id: "2" }), emp({ id: "3" })];
|
||||
(["headcount", "hires", "exits"] as Measure[]).forEach((m) => expect(measureValue(rows, m)).toBe(3));
|
||||
expect(measureValue(rows, "headcount")).toBe(3);
|
||||
});
|
||||
|
||||
it("sums FTE as weekly_hours / 38.5", () => {
|
||||
@@ -161,4 +163,74 @@ describe("aggregateReport", () => {
|
||||
])
|
||||
);
|
||||
});
|
||||
|
||||
it("reconstructs headcount/avg_age/avg_tenure as of a past Stichtag, not today", () => {
|
||||
// Entered 2019, exited 2021 — gone by today, but was active on 2020-06-01.
|
||||
const employees = [emp({ id: "1", entry_date: "2019-01-01", exit_date: "2021-01-01", birth_date: "1990-01-01" })];
|
||||
const asOf = "2020-06-01";
|
||||
const rows = aggregateReport(employees, "headcount", "division", null, lookups, asOf);
|
||||
expect(rows[0]).toMatchObject({ key: "Produktion", value: 1, count: 1 });
|
||||
expect(measureValue(employees, "avg_age", asOf)).toBe(30);
|
||||
expect(measureValue(employees, "avg_tenure", asOf)).toBeCloseTo(1.42, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveStatusAsOf", () => {
|
||||
const base = { entry_date: "2020-01-01", exit_date: null as string | null, karenz_start_date: null as string | null, karenz_return_date: null as string | null };
|
||||
|
||||
it("is Geplant before the entry date", () => {
|
||||
expect(deriveStatusAsOf({ ...base, entry_date: "2025-01-01" }, "2024-12-31")).toBe("Geplant");
|
||||
});
|
||||
|
||||
it("is Ausgetreten on/after the exit date", () => {
|
||||
expect(deriveStatusAsOf({ ...base, exit_date: "2022-06-01" }, "2022-06-01")).toBe("Ausgetreten");
|
||||
expect(deriveStatusAsOf({ ...base, exit_date: "2022-06-01" }, "2022-05-31")).toBe("Aktiv");
|
||||
});
|
||||
|
||||
it("is Karenz within the Karenz window, Aktiv once returned", () => {
|
||||
const onKarenz = { ...base, karenz_start_date: "2023-01-01", karenz_return_date: "2023-07-01" };
|
||||
expect(deriveStatusAsOf(onKarenz, "2023-03-01")).toBe("Karenz");
|
||||
expect(deriveStatusAsOf(onKarenz, "2023-07-01")).toBe("Aktiv");
|
||||
expect(deriveStatusAsOf(onKarenz, "2022-12-31")).toBe("Aktiv");
|
||||
});
|
||||
});
|
||||
|
||||
describe("aggregateEvents", () => {
|
||||
const eventLookups: OrgLookups = {
|
||||
...lookups,
|
||||
divisionName: new Map([
|
||||
["div-1", "Produktion"],
|
||||
["div-2", "IT"],
|
||||
]),
|
||||
};
|
||||
|
||||
function ev(overrides: Partial<ReportEvent> = {}): ReportEvent {
|
||||
return {
|
||||
employee_id: "1",
|
||||
first_name: "Maria",
|
||||
last_name: "Gruber",
|
||||
job_title: "Maschinenbediener:in",
|
||||
division_id: "div-1",
|
||||
team_id: "team-1",
|
||||
location_id: "loc-1",
|
||||
event_date: "2026-03-01",
|
||||
event_type: "Eintritt",
|
||||
description: "Eintritt als Maschinenbediener:in",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
it("counts every event, unlike a Bestand headcount which only sees the current entry_date", () => {
|
||||
const events = [ev({ employee_id: "1" }), ev({ employee_id: "1", event_date: "2026-05-01", event_type: "Beförderung" }), ev({ employee_id: "2", division_id: "div-2" })];
|
||||
const rows = aggregateEvents(events, "event_type", null, eventLookups);
|
||||
expect(rows.find((r) => r.key === "Eintritt")).toMatchObject({ value: 2, count: 2 });
|
||||
expect(rows.find((r) => r.key === "Beförderung")).toMatchObject({ value: 1, count: 1 });
|
||||
});
|
||||
|
||||
it("groups by the affected employee's org unit and preserves the event description on drill-down", () => {
|
||||
const events = [ev({ division_id: "div-1" }), ev({ division_id: "div-2", employee_id: "2" })];
|
||||
const rows = aggregateEvents(events, "division", null, eventLookups);
|
||||
const produktion = rows.find((r) => r.key === "Produktion")!;
|
||||
expect(produktion.people[0]).toMatchObject({ id: "1", title: "Eintritt als Maschinenbediener:in", entry_date: "2026-03-01" });
|
||||
});
|
||||
});
|
||||
|
||||
95
tests/unit/security.test.ts
Normal file
95
tests/unit/security.test.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { NextRequest } from "next/server";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { sanitizeForSpreadsheetCell, toCsv } from "@/lib/export";
|
||||
import { sanitizeIlikeTerm } from "@/lib/supabase/query";
|
||||
|
||||
// The route under test imports lib/supabase/admin.ts, which is guarded by
|
||||
// `import "server-only"` — that throws when loaded outside Next's own
|
||||
// server compilation (e.g. here, under plain Vitest/Node). Mock it out:
|
||||
// these tests only exercise the auth guard, which returns before the real
|
||||
// admin client is ever created.
|
||||
vi.mock("@/lib/supabase/admin", () => ({ createAdminClient: vi.fn() }));
|
||||
|
||||
describe("sanitizeForSpreadsheetCell", () => {
|
||||
it("prefixes values that would be read as a formula by Excel/Sheets", () => {
|
||||
expect(sanitizeForSpreadsheetCell("=SUM(A1:A2)")).toBe("'=SUM(A1:A2)");
|
||||
expect(sanitizeForSpreadsheetCell("+1234")).toBe("'+1234");
|
||||
expect(sanitizeForSpreadsheetCell("-1234")).toBe("'-1234");
|
||||
expect(sanitizeForSpreadsheetCell("@cmd")).toBe("'@cmd");
|
||||
});
|
||||
|
||||
it("leaves ordinary text untouched", () => {
|
||||
expect(sanitizeForSpreadsheetCell("Gruber")).toBe("Gruber");
|
||||
expect(sanitizeForSpreadsheetCell("Hauptstraße 1, 1200 Wien")).toBe("Hauptstraße 1, 1200 Wien");
|
||||
});
|
||||
|
||||
it("toCsv escapes a formula-injection payload in a row value", () => {
|
||||
const csv = toCsv([{ name: "=cmd|'/c calc'!A1" }], [{ header: "Name", get: (r: { name: string }) => r.name }]);
|
||||
expect(csv).toContain("'=cmd");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sanitizeIlikeTerm", () => {
|
||||
it("strips PostgREST or-filter delimiter characters", () => {
|
||||
expect(sanitizeIlikeTerm("a,b")).toBe("ab");
|
||||
expect(sanitizeIlikeTerm("a(b)c")).toBe("abc");
|
||||
// An attempt to close the current ilike condition and append another
|
||||
// column filter is neutralized by removing the delimiters, not escaped
|
||||
// into a differently-structured (but still injected) query.
|
||||
expect(sanitizeIlikeTerm("x),sv_nummer.ilike.%")).toBe("xsv_nummer.ilike.%");
|
||||
});
|
||||
|
||||
it("leaves a normal search term untouched", () => {
|
||||
expect(sanitizeIlikeTerm("Gruber")).toBe("Gruber");
|
||||
});
|
||||
});
|
||||
|
||||
describe("cron auth guard (/api/cron/apply-pending-changes)", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
async function callCronRoute(authorization?: string) {
|
||||
// The route reads process.env.CRON_SECRET inside the handler on every
|
||||
// request (not at module load time), so importing it once and reusing
|
||||
// it across the stubbed-env cases below is safe.
|
||||
const { GET } = await import("@/app/api/cron/apply-pending-changes/route");
|
||||
const headers = new Headers();
|
||||
if (authorization !== undefined) headers.set("authorization", authorization);
|
||||
const request = new NextRequest("http://localhost/api/cron/apply-pending-changes", { headers });
|
||||
return GET(request);
|
||||
}
|
||||
|
||||
it("rejects the request when CRON_SECRET is not configured, even with a matching-looking header", async () => {
|
||||
vi.stubEnv("CRON_SECRET", "");
|
||||
const res = await callCronRoute("Bearer ");
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("rejects a request with no Authorization header", async () => {
|
||||
vi.stubEnv("CRON_SECRET", "test-secret");
|
||||
const res = await callCronRoute(undefined);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("rejects a request with the wrong bearer token", async () => {
|
||||
vi.stubEnv("CRON_SECRET", "test-secret");
|
||||
const res = await callCronRoute("Bearer wrong-value");
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("protected export route without a session (/api/export/employees)", () => {
|
||||
it("returns 401 instead of running the query when there is no authenticated user", async () => {
|
||||
vi.doMock("@/lib/supabase/server", () => ({
|
||||
createClient: async () => ({
|
||||
auth: { getUser: async () => ({ data: { user: null } }) },
|
||||
}),
|
||||
}));
|
||||
const { GET } = await import("@/app/api/export/employees/route");
|
||||
const request = new NextRequest("http://localhost/api/export/employees");
|
||||
const res = await GET(request);
|
||||
expect(res.status).toBe(401);
|
||||
vi.doUnmock("@/lib/supabase/server");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user