A round of interface corrections from use, plus one schema change behind them. The private email address is now optional. It was NOT NULL — the wrong default for a private detail: someone without one had to invent one, and invented data in a personnel file is worse than missing data. Both fields are relabelled to say whose they are, "Private E-Mail" and "Private Telefonnummer", because the company address does not exist until the person starts. Uniqueness stays; several NULLs coexist in a Postgres unique index, which is exactly what is wanted. The summary step still promised that "Personalnummer und Firmen-E-Mail-Adresse werden automatisch vergeben". Neither is true any more. Removed rather than reworded — the step lists what was entered, and a banner claiming otherwise is worse than no banner. Dependents move into the wizard as step three, optional. They can only be attached after the hire, because add_employee_dependent needs an id that does not exist while the form is open, so they are collected in the draft and written afterwards. That puts them outside the transaction the person is created in: if one fails the person still exists, so the message names who is missing instead of failing silently, and the SV number is checked in the step rather than after. The emergency contact gets its own step, second to last, and its relationship is a dropdown of the common ones rather than free text — otherwise "Gattin", "Ehefrau" and "Frau" end up side by side and nothing can be counted. "Sonstige" is there because a closed list would otherwise be presumptuous. On the master-data tab it now sits below the dependents rather than above: both are people around the employee, and this is the one you reach for in a hurry. Returning from a long absence: the choice read "unverändert", which made you open the file to find out what you were agreeing to. It now reads "Wie vor Abwesenheit (38,5 h)" with the hours actually worked, and the alternative is "Reduziert" — whose hours field starts empty on purpose. A number already filled in gets confirmed rather than read off the agreement it comes from. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
249 lines
10 KiB
TypeScript
249 lines
10 KiB
TypeScript
"use client";
|
|
|
|
import { useMemo, useState } from "react";
|
|
import { useRouter } from "next/navigation";
|
|
import { addEmployeeDependent, 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 { StepAngehoerige } from "./StepAngehoerige";
|
|
import { StepNotfallkontakt } from "./StepNotfallkontakt";
|
|
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", "Angehörige", "Vertrag", "Notfallkontakt", "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.
|
|
// Die private E-Mail-Adresse steht bewusst nicht mehr darunter: sie ist
|
|
// freiwillig, seit die Spalte NULL zulässt.
|
|
Boolean(draft.personnelNumber.trim() && draft.firstName && draft.lastName && draft.birthDate && draft.locationId) &&
|
|
svNummerOk,
|
|
Boolean(draft.positionId && draft.besetzung),
|
|
// Angehörige: freiwillig — aber eine begonnene Zeile muss vollständig
|
|
// sein, sonst scheitert sie erst nach dem Anlegen der Person, und die
|
|
// steht dann schon in der Datenbank.
|
|
draft.angehoerige.every(
|
|
(a) =>
|
|
a.firstName.trim() &&
|
|
a.lastName.trim() &&
|
|
a.birthDate &&
|
|
(!a.svNummer.trim() || isValidSvnr(a.svNummer, a.birthDate || null))
|
|
),
|
|
Boolean(draft.entryDate && draft.workDays.length > 0),
|
|
// Notfallkontakt: freiwillig, aber Name und Nummer nur gemeinsam — die
|
|
// Datenbank weist eines ohne das andere ab (chk_emergency_contact).
|
|
Boolean(draft.emergencyContactName.trim()) === Boolean(draft.emergencyContactPhone.trim()),
|
|
true,
|
|
][step];
|
|
|
|
/** Der letzte Schritt; von hier wird angelegt statt weitergeblättert. */
|
|
const letzterSchritt = STEP_LABELS.length - 1;
|
|
|
|
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({
|
|
personnel_number: Number(draft.personnelNumber),
|
|
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() || undefined,
|
|
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,
|
|
// Null, sobald kein Dienstwagen da ist — der CHECK lässt die Angabe
|
|
// sonst nicht zu.
|
|
dienstwagen_art: draft.hasDienstwagen ? draft.dienstwagenArt : null,
|
|
emergency_contact_name: draft.emergencyContactName.trim() || undefined,
|
|
emergency_contact_phone: draft.emergencyContactPhone.trim() || undefined,
|
|
emergency_contact_relation: draft.emergencyContactRelation.trim() || undefined,
|
|
is_laterale_fuehrung: draft.isLateraleFuehrung,
|
|
is_c_level: draft.isCLevel,
|
|
});
|
|
if (!result.success || !result.employeeId) {
|
|
setSubmitting(false);
|
|
showToast(result.error ?? "Fehler beim Anlegen.", "error");
|
|
return;
|
|
}
|
|
|
|
// Angehörige erst jetzt: add_employee_dependent braucht die Kennung, und
|
|
// die entsteht mit der Einstellung.
|
|
//
|
|
// Damit hängen sie ausserhalb der Transaktion, in der die Person
|
|
// entsteht. Scheitert eine, ist die Person trotzdem angelegt — deshalb
|
|
// wird nicht stillschweigend weitergemacht, sondern genau gesagt, wer
|
|
// fehlt. Nachtragen geht in der Personalakte.
|
|
const gescheitert: string[] = [];
|
|
for (const a of draft.angehoerige) {
|
|
const r = await addEmployeeDependent({
|
|
employee_id: result.employeeId,
|
|
first_name: a.firstName.trim(),
|
|
last_name: a.lastName.trim(),
|
|
relationship: a.relationship,
|
|
birth_date: a.birthDate,
|
|
sv_nummer: a.svNummer.trim() || undefined,
|
|
effective_date: draft.entryDate,
|
|
});
|
|
if (!r.success) gescheitert.push(`${a.firstName} ${a.lastName}`.trim());
|
|
}
|
|
|
|
setSubmitting(false);
|
|
if (draftId) await deleteHireDraft(draftId);
|
|
router.refresh();
|
|
onClose();
|
|
|
|
if (gescheitert.length > 0) {
|
|
showToast(
|
|
`${draft.firstName} ${draft.lastName} wurde eingestellt, aber ${gescheitert.join(", ")} konnte nicht als Angehörige:r angelegt werden — bitte in der Personalakte nachtragen.`,
|
|
"error"
|
|
);
|
|
} else {
|
|
showToast(`${draft.firstName} ${draft.lastName} wurde eingestellt.`);
|
|
}
|
|
}
|
|
|
|
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 < letzterSchritt && (
|
|
<Button onClick={() => setStep((s) => s + 1)} disabled={!stepValid}>
|
|
Weiter
|
|
</Button>
|
|
)}
|
|
{step === letzterSchritt && (
|
|
<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 && <StepAngehoerige draft={draft} update={update} />}
|
|
{step === 3 && <StepVertrag draft={draft} update={update} />}
|
|
{step === 4 && <StepNotfallkontakt draft={draft} update={update} />}
|
|
{step === 5 && <StepSummary draft={draft} selectedPosition={selectedPosition} locations={locations} />}
|
|
</Modal>
|
|
);
|
|
}
|