Talk to PostgreSQL directly, and let the pooled connection forget

Zweiter Schritt weg von Supabase. Sämtliche 49 Lesezugriffe und alle
Mutationen laufen jetzt über lib/db statt über die REST-Schicht: Kysely auf
einem pg-Pool, jede Abfrage in einer Transaktion, in der zuerst
app.user_id gesetzt wird. Die Anmeldung hängt noch an GoTrue — sie liefert
die Kennung, die in withUser() geht. Damit war der Umbau in zwei Hälften
teilbar und die Anwendung durchgehend lauffähig.

Was dabei ersatzlos verschwindet:

  - fetchAllRows. Es gab die Funktion nur, weil PostgREST jede Antwort bei
    1000 Zeilen still abschneidet und ein Bericht dann leise falsch war.
    Am direkten Zugang ist eine Abfrage eine Abfrage.
  - sanitizeIlikeTerm samt Test. Sie entschärfte Zeichen, die in der
    Filtersyntax strukturelle Bedeutung hatten; jetzt wird der Suchbegriff
    als Parameter gebunden und ein Komma ist ein Komma. Die Lücke ist nicht
    abgesichert, sondern weg.
  - lib/supabase/admin.ts. Der Dienstschlüssel, der RLS aushebelte, hatte
    genau einen Aufrufer — den nächtlichen Lauf. Der benutzt jetzt dieselbe
    Rolle ohne BYPASSRLS und ruft eine SECURITY-DEFINER-Funktion auf, die
    selbst prüft, was sie tut. Es gibt keinen privilegierten Zugang mehr.

Nebenbei besser geworden, weil der direkte Zugang es erlaubt:

  - Eine Seite ist eine Transaktion. Das Layout etwa liest Profil,
    Planstellen, Standorte, Entwürfe und Notizen auf einem einheitlichen
    Lesestand statt in fünf unabhängigen Anfragen.
  - Der Bereichsfilter der Mitarbeiterliste ist ein EXISTS statt einer
    eingebetteten Ressource mit !inner — eine Person mit mehreren
    Zuordnungen über die Zeit erschien dort mehrfach.
  - Seitenweise Listen sortieren zusätzlich nach id. Bei gleichem Nachnamen
    oder gleichem Zeitstempel war die Reihenfolge vorher unbestimmt, und
    dieselbe Zeile konnte auf zwei Seiten erscheinen oder auf keiner.
  - Angehörige werden in der Datenbank gezählt statt alle Zeilen zu holen.
  - Namen an Ereigniszeilen kommen aus einem Join statt aus einem
    Nachschlag, der ausserhalb der Transaktion lag.

Der Statusfilter ist mitgezogen: dieselbe Regel wie deriveStatusAsOf,
Klausel für Klausel, jetzt als Kysely-Ausdruck. Der Integrationstest, der
beide über den gesamten Bestand vergleicht, läuft weiter — mit eigener
Verbindung, denn geprüft wird die Bedingung, nicht die Berechtigung.

Zwei Fehler auf dem Weg, beide vom Typprüfer gefangen: apply_due_pending_
changes() nimmt kein Argument, wurde von callFunction aber mit jsonb
aufgerufen — Postgres hätte keine passende Signatur gefunden. Und der
Sicherheitstest lädt jetzt Module mit `import "server-only"`, was ausserhalb
der Server-Übersetzung wirft.

Typecheck, Lint, Build und 180 Tests sind grün. Ungeprüft bleibt der Lauf
gegen eine echte Datenbank — dafür fehlt eine DATABASE_URL.
This commit is contained in:
2026-07-31 08:45:26 +02:00
parent a66263a96e
commit b3a0af2b8f
31 changed files with 1086 additions and 803 deletions

View File

@@ -8,8 +8,9 @@ import { divisionOf, loadOrgMaps } from "@/lib/org";
import { loadPlacements } from "@/lib/placement";
import { loadOpenPositions } from "@/lib/positions";
import { deriveStatusAsOf } from "@/lib/reports";
import { createClient } from "@/lib/supabase/server";
import { fetchAllRows } from "@/lib/supabase/query";
import { currentUserId } from "@/lib/auth/session";
import { withUser } from "@/lib/db";
import type { HistoryEventType } from "@/lib/supabase/types";
// Each KPI carries a colour already; the accent bar repeats it in a second
// channel so the tiles are scannable as a row rather than six identical
@@ -39,18 +40,6 @@ const DOT_STYLES: Record<string, string> = {
const KIND_LABEL = { hire: "Eintritt", exit: "Austritt", return: "Rückkehr aus Abwesenheit" } as const;
export default async function DashboardPage() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
const { data: drafts } = user
? await supabase
.from("hire_drafts")
.select("id, step, payload, updated_at")
.eq("created_by", user.id)
.order("updated_at", { ascending: false })
: { data: [] };
// Built as strings, not by round-tripping a local Date through
// toISOString(): in any positive-offset zone new Date(year, 0, 1) is still
// the previous year in UTC, which shifted the whole YTD window a day early
@@ -61,6 +50,8 @@ export default async function DashboardPage() {
const yearEnd = `${year}-12-31`;
const in60Iso = addDaysIso(today, 60);
const userId = await currentUserId();
// Headcount, FTE, Karenz and the division bars all come from one full read
// and the *derived* status, not from the `employees.status` column.
//
@@ -69,70 +60,116 @@ export default async function DashboardPage() {
// planned hire whose start date has passed, or a Karenz that ended without
// anyone recording the return, made the dashboard and the Berichte page
// disagree about the same headcount. Same derivation, same numbers.
// It also replaces four separate count queries with one.
const [
const {
drafts,
staffRows,
hiresYtdRes,
exitsYtdRes,
hiresYtd,
exitsYtd,
openPositions,
orgMaps,
placements,
upcomingHiresRes,
upcomingExitsRes,
upcomingReturnsRes,
historyRes,
] = await Promise.all([
fetchAllRows(() =>
supabase
.from("employees")
.select("id, weekly_hours, entry_date, exit_date, karenz_start_date, karenz_return_date")
.order("id")
),
// Entries/exits count history events, which is what the linked report
// counts too. `entry_date` would also sweep up rehires, whose event is
// logged as 'Wiedereintritt' — the tile and its destination then showed
// different numbers for the same year.
supabase
.from("employee_history")
.select("id", { count: "exact", head: true })
.in("event_type", ["Eintritt", "Wiedereintritt"])
.gte("event_date", yearStart)
.lte("event_date", yearEnd),
supabase
.from("employee_history")
.select("id", { count: "exact", head: true })
.eq("event_type", "Austritt")
.gte("event_date", yearStart)
.lte("event_date", yearEnd),
loadOpenPositions(supabase),
loadOrgMaps(supabase),
loadPlacements(supabase, { asOf: today }),
supabase
.from("employees")
.select("id, first_name, last_name, entry_date")
.eq("status", "Geplant")
.gte("entry_date", today)
.lte("entry_date", in60Iso),
supabase
.from("employees")
.select("id, first_name, last_name, exit_date")
.not("exit_date", "is", null)
.gte("exit_date", today)
.lte("exit_date", in60Iso),
supabase
.from("employees")
.select("id, first_name, last_name, karenz_return_date")
.eq("status", "Karenz")
.not("karenz_return_date", "is", null)
.gte("karenz_return_date", today)
.lte("karenz_return_date", in60Iso),
supabase
.from("employee_history")
.select("id, employee_id, event_date, event_type, description")
.order("event_date", { ascending: false })
.order("created_at", { ascending: false })
.limit(10),
]);
upcomingHires,
upcomingExits,
upcomingReturns,
history,
} = await withUser(userId, async (tx) => {
const countIn = (types: readonly HistoryEventType[]) =>
tx
.selectFrom("employee_history")
.select(({ fn }) => fn.countAll<string>().as("anzahl"))
.where("event_type", "in", [...types])
.where("event_date", ">=", yearStart)
.where("event_date", "<=", yearEnd)
.executeTakeFirst();
const [
drafts,
staffRows,
hiresYtd,
exitsYtd,
openPositions,
orgMaps,
placements,
upcomingHires,
upcomingExits,
upcomingReturns,
history,
] = await Promise.all([
userId
? tx
.selectFrom("hire_drafts")
.select(["id", "step", "payload", "updated_at"])
.where("created_by", "=", userId)
.orderBy("updated_at", "desc")
.execute()
: Promise.resolve([]),
tx
.selectFrom("employees")
.select(["id", "weekly_hours", "entry_date", "exit_date", "karenz_start_date", "karenz_return_date"])
.orderBy("id")
.execute(),
// Entries/exits count history events, which is what the linked report
// counts too. `entry_date` would also sweep up rehires, whose event is
// logged as 'Wiedereintritt' — the tile and its destination then showed
// different numbers for the same year.
countIn(["Eintritt", "Wiedereintritt"]),
countIn(["Austritt"]),
loadOpenPositions(tx),
loadOrgMaps(tx),
loadPlacements(tx, { asOf: today }),
tx
.selectFrom("employees")
.select(["id", "first_name", "last_name", "entry_date"])
.where("status", "=", "Geplant")
.where("entry_date", ">=", today)
.where("entry_date", "<=", in60Iso)
.execute(),
tx
.selectFrom("employees")
.select(["id", "first_name", "last_name", "exit_date"])
.where("exit_date", "is not", null)
.where("exit_date", ">=", today)
.where("exit_date", "<=", in60Iso)
.execute(),
tx
.selectFrom("employees")
.select(["id", "first_name", "last_name", "karenz_return_date"])
.where("status", "=", "Karenz")
.where("karenz_return_date", "is not", null)
.where("karenz_return_date", ">=", today)
.where("karenz_return_date", "<=", in60Iso)
.execute(),
tx
.selectFrom("employee_history as h")
.leftJoin("employees as e", "e.id", "h.employee_id")
.select(["h.id", "h.employee_id", "h.event_date", "h.event_type", "h.description", "e.first_name", "e.last_name"])
.orderBy("h.event_date", "desc")
.orderBy("h.created_at", "desc")
.limit(10)
.execute(),
]);
return {
drafts,
staffRows,
hiresYtd: Number(hiresYtd?.anzahl ?? 0),
exitsYtd: Number(exitsYtd?.anzahl ?? 0),
openPositions,
orgMaps,
placements,
upcomingHires,
upcomingExits,
upcomingReturns,
history,
};
});
// "Aktiv" means status Aktiv — somebody on Karenz is employed but not
// active, and is counted by its own tile instead. FTE follows the same
@@ -166,19 +203,19 @@ export default async function DashboardPage() {
type UpcomingItem = { id: string; label: string; date: string; kind: keyof typeof KIND_LABEL };
const upcoming: UpcomingItem[] = [
...(upcomingHiresRes.data ?? []).map((e) => ({
...(upcomingHires).map((e) => ({
id: e.id,
label: `${e.first_name} ${e.last_name}`,
date: e.entry_date,
kind: "hire" as const,
})),
...(upcomingExitsRes.data ?? []).map((e) => ({
...(upcomingExits).map((e) => ({
id: e.id,
label: `${e.first_name} ${e.last_name}`,
date: e.exit_date!,
kind: "exit" as const,
})),
...(upcomingReturnsRes.data ?? []).map((e) => ({
...(upcomingReturns).map((e) => ({
id: e.id,
label: `${e.first_name} ${e.last_name}`,
date: e.karenz_return_date!,
@@ -188,12 +225,6 @@ export default async function DashboardPage() {
.sort((a, b) => a.date.localeCompare(b.date))
.slice(0, 8);
const historyEmployeeIds = Array.from(new Set((historyRes.data ?? []).map((h) => h.employee_id)));
const historyEmployeesRes = historyEmployeeIds.length
? await supabase.from("employees").select("id, first_name, last_name").in("id", historyEmployeeIds)
: { data: [] as { id: string; first_name: string; last_name: string }[] };
const employeeNameById = new Map((historyEmployeesRes.data ?? []).map((e) => [e.id, `${e.first_name} ${e.last_name}`]));
// Each tile links to the view that shows what it counts, with the filters
// pre-applied.
//
@@ -214,13 +245,13 @@ export default async function DashboardPage() {
{ label: "FTE", value: fte.toFixed(1), tone: "default", href: "/reports?mode=snapshot&measure=fte&status=Aktiv" },
{
label: "Eintritte (Jahr)",
value: hiresYtdRes.count ?? 0,
value: hiresYtd,
tone: "success",
href: `/reports?mode=events&eventType=Eintritt&from=${yearStart}&to=${yearEnd}`,
},
{
label: "Austritte (Jahr)",
value: exitsYtdRes.count ?? 0,
value: exitsYtd,
tone: "danger",
href: `/reports?mode=events&eventType=Austritt&from=${yearStart}&to=${yearEnd}`,
},
@@ -300,14 +331,14 @@ export default async function DashboardPage() {
<Card>
<CardTitle className="mb-1">Letzte Aktivitäten</CardTitle>
<ul className="flex flex-col divide-y divide-border-subtle">
{(historyRes.data ?? []).map((h) => (
{(history).map((h) => (
<li key={h.id} className="flex gap-2.5 py-2.5">
{/* Dot aligned to the first line of text, not centred on the
whole row, so it stays put as descriptions wrap. */}
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT_STYLES[h.event_type] ?? "bg-ink-muted"}`} aria-hidden />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="text-sm font-semibold text-ink">{employeeNameById.get(h.employee_id) ?? "Unbekannt"}</span>
<span className="text-sm font-semibold text-ink">{h.first_name && h.last_name ? `${h.first_name} ${h.last_name}` : "Unbekannt"}</span>
<span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${actionBadgeStyle(h.event_type)}`}>
{h.event_type}
</span>
@@ -316,7 +347,7 @@ export default async function DashboardPage() {
</div>
</li>
))}
{(historyRes.data ?? []).length === 0 && <p className="py-2 text-sm text-ink-muted">Keine Aktivitäten vorhanden.</p>}
{(history).length === 0 && <p className="py-2 text-sm text-ink-muted">Keine Aktivitäten vorhanden.</p>}
</ul>
</Card>
</div>