Files
alpenwerk-hr/components/hire/HireWizard.tsx
Maximilian Stubhan e44f71a60d Stop offering positions that are already spoken for, and let hiring work again
Two reports, four defects, all of them in the way of ordinary use.

A position with a signed starter is not vacant. loadOpenPositions asked "is
anyone on it today?", so three positions whose new holders begin in
September and October were listed as open, labelled "vacant for 2 days".
That same list feeds the hire wizard, so it invited filling a position a
second time — discovered at the partial unique index, after the second
interview. Vacancy now means no assignment that still stands, including one
that has not started. An assignment that ended still frees the position.

Hiring was broken three times over, each fault hidden behind the previous
one:

  1. hire_employee cast to ::weekday[], a type that no longer exists — it
     was replaced by text plus a CHECK constraint and the function was never
     updated. apply_due_pending_changes had the same problem with
     ::relationship_type, which would have broken the nightly run.
     PL/pgSQL resolves types in embedded statements at execution time, so
     both functions were created without complaint and failed only in use.
  2. Fourteen functions called auth.uid(). The application connects as a
     role with no rights on the auth schema, so every write — hire,
     transfer, promote, exit, notes, positions — failed with "permission
     denied for schema auth". They now use app_current_user_id(), which is
     where #23 was heading anyway. Its own fallback also caught only
     "function missing" and now catches the privilege error too, so a call
     without session context returns null instead of raising.
  3. The audit line built a name as `payload->>'a' || ' ' || payload->>'b'`.
     `||` binds tighter than `->>`, so Postgres reads
     `payload ->> ('a' || ' ' || payload) ->> 'b'`. The ACL failure above
     had aborted analysis before the parser ever reached it.

And the wizard collected an email, showed it in the summary, and dropped it:
the server action's signature had no such field. employees.email is NOT
NULL, so every hire that got past the three faults above would have failed
there. It is now passed through and required in step one, rather than
refused by the database at the end of step four.

Verified against the live database, each rolled back: a hire now creates the
employee, the assignment, the history entry and an audit line reading "Probe
Einstellung"; open positions drop from 13 to 10, and the three that
disappear are exactly the ones with a starter.

Migrations rewrite the affected functions in place rather than restating
them — retyping 165 lines of working PL/pgSQL to change two words is the
larger risk. Each one asserts the result afterwards.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-05 12:10:17 +02:00

189 lines
7.2 KiB
TypeScript

"use client";
import { useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import { hireEmployee } from "@/actions/employees";
import { deleteHireDraft, saveHireDraft } from "@/actions/hireDrafts";
import { Button } from "@/components/ui/Button";
import { Modal } from "@/components/ui/Modal";
import { useToast } from "@/components/ui/Toast";
import type { OpenPositionResolved } from "@/lib/positions";
import { isValidSvnr, requiresAustrianSvnr } from "@/lib/svnr";
import { StepPerson } from "./StepPerson";
import { StepPosition } from "./StepPosition";
import { StepSummary } from "./StepSummary";
import { StepVertrag } from "./StepVertrag";
import { EMPTY_HIRE_DRAFT, type HireDraftData } from "./types";
const STEP_LABELS = ["Person", "Position", "Vertrag", "Zusammenfassung"];
type HireWizardProps = {
open: boolean;
onClose: () => void;
openPositions: OpenPositionResolved[];
locations: { id: string; name: string; country: string }[];
resumeDraft: { id: string; step: number; payload: Record<string, unknown> } | null;
initialPositionId?: string;
};
export function HireWizard({ open, onClose, openPositions, locations, resumeDraft, initialPositionId }: HireWizardProps) {
const { showToast } = useToast();
const router = useRouter();
// The parent remounts this component (via a changing `key`) each time it's
// freshly opened, so these initializers — reading resumeDraft/
// initialPositionId once at mount — are the reset, no effect needed.
const [step, setStep] = useState(() => resumeDraft?.step ?? 0);
const [draft, setDraft] = useState<HireDraftData>(() =>
resumeDraft
? { ...EMPTY_HIRE_DRAFT, ...(resumeDraft.payload as Partial<HireDraftData>) }
: { ...EMPTY_HIRE_DRAFT, positionId: initialPositionId ?? "" }
);
const [draftId] = useState<string | undefined>(() => resumeDraft?.id);
const [submitting, setSubmitting] = useState(false);
const selectedPosition = useMemo(
() => openPositions.find((p) => p.id === draft.positionId) ?? null,
[openPositions, draft.positionId]
);
function update(patch: Partial<HireDraftData>) {
setDraft((prev) => ({ ...prev, ...patch }));
}
// Blocks step 1 rather than letting the hire fail at the RPC: the SVNR
// trigger rejects a bad number, and by then the user is three steps on.
const svNummerOk =
!draft.svNummer.trim() ||
!requiresAustrianSvnr(locations.find((l) => l.id === draft.locationId)?.country) ||
isValidSvnr(draft.svNummer, draft.birthDate || null);
const stepValid = [
// E-Mail gehört zu den Pflichtfeldern, weil die Spalte NOT NULL ist. Ohne
// die Prüfung hier bricht erst die Datenbank ab — am Ende des vierten
// Schritts, nach allen Eingaben.
Boolean(draft.firstName && draft.lastName && draft.birthDate && draft.locationId && draft.email.trim()) &&
svNummerOk,
Boolean(draft.positionId && draft.besetzung),
Boolean(draft.entryDate && draft.workDays.length > 0),
true,
][step];
async function handleSaveDraft() {
const result = await saveHireDraft({ id: draftId, step, data: draft });
if (result.success) {
showToast("Entwurf gespeichert.");
router.refresh();
onClose();
} else {
showToast(result.error ?? "Fehler beim Speichern.", "error");
}
}
async function handleSubmit() {
if (!selectedPosition || !draft.besetzung) return;
setSubmitting(true);
const result = await hireEmployee({
first_name: draft.firstName,
last_name: draft.lastName,
title_prefix: draft.titlePrefix,
title_suffix: draft.titleSuffix,
gender: draft.gender,
birth_date: draft.birthDate,
sv_nummer: draft.svNummer || undefined,
email: draft.email.trim(),
phone: draft.phone || undefined,
position_id: draft.positionId,
location_id: draft.locationId,
entry_date: draft.entryDate,
contract_type: draft.contractType,
contract_end_date: draft.contractType === "befristet" ? draft.contractEndDate : undefined,
employment_type: draft.employmentType,
weekly_hours: Number(draft.weeklyHours),
paygrade: draft.paygrade,
source: draft.besetzung,
worker_type: draft.workerType,
collective_agreement: draft.collectiveAgreement,
work_days: draft.workDays,
is_betriebsrat: draft.isBetriebsrat,
has_dienstwagen: draft.hasDienstwagen,
is_laterale_fuehrung: draft.isLateraleFuehrung,
is_c_level: draft.isCLevel,
});
setSubmitting(false);
if (result.success) {
showToast(`${draft.firstName} ${draft.lastName} wurde eingestellt.`);
if (draftId) await deleteHireDraft(draftId);
router.refresh();
onClose();
} else {
showToast(result.error ?? "Fehler beim Anlegen.", "error");
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Neueinstellung"
widthClassName="max-w-2xl"
footer={
<div className="flex w-full items-center justify-between">
<div className="flex gap-2">
<Button variant="ghost" onClick={onClose}>
Abbrechen
</Button>
<Button variant="ghost" onClick={handleSaveDraft}>
Als Entwurf speichern
</Button>
</div>
<div className="flex gap-2">
{step > 0 && (
<Button variant="secondary" onClick={() => setStep((s) => s - 1)}>
Zurück
</Button>
)}
{step < 3 && (
<Button onClick={() => setStep((s) => s + 1)} disabled={!stepValid}>
Weiter
</Button>
)}
{step === 3 && (
<Button onClick={handleSubmit} pending={submitting}>
Anlegen
</Button>
)}
</div>
</div>
}
>
{/* A progress trail, not navigation: only completed steps are
reachable, so the rest are genuinely disabled rather than inert
buttons that silently swallow a click. */}
<div className="mb-6 flex items-center justify-center gap-3">
{STEP_LABELS.map((label, i) => (
<button
key={label}
type="button"
disabled={i >= step}
aria-current={i === step ? "step" : undefined}
onClick={() => i < step && setStep(i)}
className={`flex items-center gap-2 rounded text-xs font-semibold focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 disabled:cursor-default ${
i === step ? "text-brand-700" : i < step ? "text-ink-body" : "text-ink-muted"
}`}
>
<span className={`flex h-6 w-6 items-center justify-center rounded-full ${i <= step ? "bg-brand-500 text-white" : "bg-surface text-ink-muted"}`}>
{i + 1}
</span>
{label}
</button>
))}
</div>
{step === 0 && <StepPerson draft={draft} update={update} locations={locations} />}
{step === 1 && <StepPosition draft={draft} update={update} openPositions={openPositions} />}
{step === 2 && <StepVertrag draft={draft} update={update} />}
{step === 3 && <StepSummary draft={draft} selectedPosition={selectedPosition} locations={locations} />}
</Modal>
);
}