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:
@@ -1,9 +1,8 @@
|
||||
import type { SupabaseClient } from "@supabase/supabase-js";
|
||||
import type { Tx } from "./db";
|
||||
import { ancestorsOf, loadOrgMaps, subtreeOf, type OrgMaps } from "./org";
|
||||
import { loadPlacements } from "./placement";
|
||||
import { deriveStatusAsOf, EVENT_DATE_OPEN, parseStatuses, todayIso, type OrgLookups, type ReportEmployee, type ReportEvent } from "./reports";
|
||||
import { fetchAllRows } from "./supabase/query";
|
||||
import type { Database, EmploymentType, HistoryEventType } from "./supabase/types";
|
||||
import type { 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
|
||||
@@ -40,13 +39,13 @@ export function lookupsFromOrgMaps(orgMaps: OrgMaps, locations: { id: string; na
|
||||
return { divisionName, departmentName, teamName, locationName: new Map(locations.map((l) => [l.id, l.name])) };
|
||||
}
|
||||
|
||||
export async function loadOrgLookups(supabase: SupabaseClient<Database>): Promise<{
|
||||
export async function loadOrgLookups(tx: Tx): Promise<{
|
||||
lookups: OrgLookups;
|
||||
orgMaps: OrgMaps;
|
||||
divisions: { id: string; name: string }[];
|
||||
locations: { id: string; name: string }[];
|
||||
}> {
|
||||
const orgMaps = await loadOrgMaps(supabase);
|
||||
const orgMaps = await loadOrgMaps(tx);
|
||||
const locations = orgMaps.locationList.map((l) => ({ id: l.id, name: l.name }));
|
||||
|
||||
return {
|
||||
@@ -60,37 +59,61 @@ export async function loadOrgLookups(supabase: SupabaseClient<Database>): Promis
|
||||
};
|
||||
}
|
||||
|
||||
const SNAPSHOT_EMPLOYEE_COLUMNS =
|
||||
"id, first_name, last_name, job_title, location_id, employment_type, contract_type, entry_date, exit_date, weekly_hours, source, paygrade, birth_date, gender, karenz_start_date, karenz_return_date, worker_type, collective_agreement, work_days, is_betriebsrat, has_dienstwagen, is_laterale_fuehrung, is_c_level";
|
||||
const SNAPSHOT_EMPLOYEE_COLUMNS = [
|
||||
"id",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"job_title",
|
||||
"location_id",
|
||||
"employment_type",
|
||||
"contract_type",
|
||||
"entry_date",
|
||||
"exit_date",
|
||||
"weekly_hours",
|
||||
"source",
|
||||
"paygrade",
|
||||
"birth_date",
|
||||
"gender",
|
||||
"karenz_start_date",
|
||||
"karenz_return_date",
|
||||
"worker_type",
|
||||
"collective_agreement",
|
||||
"work_days",
|
||||
"is_betriebsrat",
|
||||
"has_dienstwagen",
|
||||
"is_laterale_fuehrung",
|
||||
"is_c_level",
|
||||
] as const;
|
||||
|
||||
// employee_id -> number of employee_dependents rows. Selects only the FK
|
||||
// column (no dependent PII needed) since only per-employee counts feed the
|
||||
// has_dependents/avg_dependents report dimensions; counted client-side
|
||||
// since the Supabase JS client has no `count(*) group by employee_id`
|
||||
// shorthand. Shared by the Bestand pivot and the full employees export.
|
||||
export async function loadDependentsCounts(supabase: SupabaseClient<Database>): Promise<Map<string, number>> {
|
||||
const rows = await fetchAllRows(() => supabase.from("employee_dependents").select("employee_id").order("employee_id"));
|
||||
const counts = new Map<string, number>();
|
||||
for (const d of rows) counts.set(d.employee_id, (counts.get(d.employee_id) ?? 0) + 1);
|
||||
return counts;
|
||||
// Anzahl der Angehörigen je Person. Nur der Fremdschlüssel wird gelesen —
|
||||
// für die Berichtsdimensionen zählt die Anzahl, nicht wer es ist.
|
||||
export async function loadDependentsCounts(tx: Tx): Promise<Map<string, number>> {
|
||||
// Am direkten Zugang zählt die Datenbank, statt dass die Anwendung alle
|
||||
// Zeilen holt und sie selbst durchgeht.
|
||||
const rows = await tx
|
||||
.selectFrom("employee_dependents")
|
||||
.select(({ fn }) => ["employee_id", fn.countAll<string>().as("anzahl")])
|
||||
.groupBy("employee_id")
|
||||
.execute();
|
||||
return new Map(rows.map((r) => [r.employee_id, Number(r.anzahl)]));
|
||||
}
|
||||
|
||||
// Bestand zum Stichtag: Status *und* Einordnung werden auf `asOf` aufgelöst.
|
||||
export async function loadSnapshotEmployees(supabase: SupabaseClient<Database>, filters: SnapshotFilters): Promise<ReportEmployee[]> {
|
||||
export async function loadSnapshotEmployees(tx: Tx, filters: SnapshotFilters): Promise<ReportEmployee[]> {
|
||||
const asOf = filters.asOf || todayIso();
|
||||
|
||||
function snapshotQuery() {
|
||||
let query = supabase.from("employees").select(SNAPSHOT_EMPLOYEE_COLUMNS).order("id");
|
||||
if (filters.location) query = query.eq("location_id", filters.location);
|
||||
if (filters.employment) query = query.eq("employment_type", filters.employment as EmploymentType);
|
||||
return query;
|
||||
let q = tx.selectFrom("employees").select([...SNAPSHOT_EMPLOYEE_COLUMNS]).orderBy("id");
|
||||
if (filters.location) q = q.where("location_id", "=", filters.location);
|
||||
if (filters.employment) q = q.where("employment_type", "=", filters.employment as EmploymentType);
|
||||
return q;
|
||||
}
|
||||
|
||||
const [data, dependentsCounts, placements, orgMaps] = await Promise.all([
|
||||
fetchAllRows(snapshotQuery),
|
||||
loadDependentsCounts(supabase),
|
||||
loadPlacements(supabase, { asOf }),
|
||||
filters.division ? loadOrgMaps(supabase) : Promise.resolve(null),
|
||||
snapshotQuery().execute(),
|
||||
loadDependentsCounts(tx),
|
||||
loadPlacements(tx, { asOf }),
|
||||
filters.division ? loadOrgMaps(tx) : Promise.resolve(null),
|
||||
]);
|
||||
|
||||
// Der Bereichsfilter meint den ganzen Teilbaum: „Produktion" schliesst
|
||||
@@ -146,40 +169,38 @@ export async function loadSnapshotEmployees(supabase: SupabaseClient<Database>,
|
||||
// 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[]> {
|
||||
export async function loadEventHistory(tx: Tx, 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`;
|
||||
|
||||
function historyQuery() {
|
||||
let query = supabase.from("employee_history").select("employee_id, event_date, event_type, description").order("id");
|
||||
if (from) query = query.gte("event_date", from);
|
||||
if (to) query = query.lte("event_date", to);
|
||||
if (filters.eventType) query = query.eq("event_type", filters.eventType);
|
||||
return query;
|
||||
let q = tx
|
||||
.selectFrom("employee_history")
|
||||
.select(["employee_id", "event_date", "event_type", "description"])
|
||||
.orderBy("id");
|
||||
if (from) q = q.where("event_date", ">=", from);
|
||||
if (to) q = q.where("event_date", "<=", to);
|
||||
if (filters.eventType) q = q.where("event_type", "=", filters.eventType);
|
||||
return q;
|
||||
}
|
||||
|
||||
const [history, employees, assignments, orgMaps] = await Promise.all([
|
||||
fetchAllRows(historyQuery),
|
||||
fetchAllRows(() => supabase.from("employees").select("id, first_name, last_name, job_title, location_id").order("id")),
|
||||
fetchAllRows(() =>
|
||||
supabase
|
||||
.from("position_assignments")
|
||||
.select("employee_id, valid_from, valid_to, om_positions!inner(org_unit_id)")
|
||||
.order("employee_id")
|
||||
),
|
||||
filters.division ? loadOrgMaps(supabase) : Promise.resolve(null),
|
||||
historyQuery().execute(),
|
||||
tx.selectFrom("employees").select(["id", "first_name", "last_name", "job_title", "location_id"]).orderBy("id").execute(),
|
||||
tx
|
||||
.selectFrom("position_assignments as a")
|
||||
.innerJoin("om_positions as p", "p.id", "a.position_id")
|
||||
.select(["a.employee_id", "a.valid_from", "a.valid_to", "p.org_unit_id"])
|
||||
.orderBy("a.employee_id")
|
||||
.execute(),
|
||||
filters.division ? loadOrgMaps(tx) : Promise.resolve(null),
|
||||
]);
|
||||
|
||||
const spans = new Map<string, { from: string; to: string | null; unitId: string }[]>();
|
||||
for (const a of assignments as unknown as {
|
||||
employee_id: string;
|
||||
valid_from: string;
|
||||
valid_to: string | null;
|
||||
om_positions: { org_unit_id: string };
|
||||
}[]) {
|
||||
for (const a of assignments) {
|
||||
const list = spans.get(a.employee_id) ?? [];
|
||||
list.push({ from: a.valid_from, to: a.valid_to, unitId: a.om_positions.org_unit_id });
|
||||
list.push({ from: a.valid_from, to: a.valid_to, unitId: a.org_unit_id });
|
||||
spans.set(a.employee_id, list);
|
||||
}
|
||||
|
||||
@@ -193,7 +214,7 @@ export async function loadEventHistory(supabase: SupabaseClient<Database>, filte
|
||||
if (filters.location && emp.location_id !== filters.location) continue;
|
||||
|
||||
const unitId =
|
||||
spans.get(h.employee_id)?.find((s) => s.from <= h.event_date && (s.to === null || s.to > h.event_date))?.unitId ?? null;
|
||||
spans.get(h.employee_id)?.find((s2) => s2.from <= h.event_date && (s2.to === null || s2.to > h.event_date))?.unitId ?? null;
|
||||
if (allowedUnits && (!unitId || !allowedUnits.has(unitId))) continue;
|
||||
|
||||
events.push({
|
||||
|
||||
Reference in New Issue
Block a user