Works council members, expectant mothers, parents on leave, registered disabled employees, apprentices — each has its own rules that come before a dismissal. The tool does not judge whether one is lawful, but it must not stay quiet about it either, and looking it up on the contract tab is exactly the step that gets skipped under time pressure. So: a checkbox, an optional end date, and a red warning at the top of the termination panel naming the date — or saying plainly that no end was recorded. It shows for a no-show too; the protection runs from the start of the contract, not the first day worked. The date is optional on purpose. A works council mandate has a known end, a pregnancy does not, and a mandatory field would force an invented number. A constraint says only what cannot be: an end date without the flag, which would be a leftover nobody could interpret. The field goes the whole way through — hire, data change, contract sheet, export, report criteria (as a yes/no and as a date range), and the import. A field that exists in one screen and not the next is how people stop trusting the numbers. Terminating is now offered for planned entries as well, labelled "Nicht angetreten", with No Show preselected. Without it a person who never turned up stayed a planned entry forever, since nothing else can end one. One finding worth recording: tsc has been reporting success on a broken program. A generated file under .next got corrupted when a build ran against a live dev server, and its syntax errors suppressed semantic checking everywhere else — two genuine type errors in this change went unreported until I typechecked with .next excluded. The file is removed and the ordinary typecheck is meaningful again. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
252 lines
10 KiB
TypeScript
252 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,
|
|
has_kuendigungsschutz: draft.hasKuendigungsschutz,
|
|
// Ohne Schutz kein Enddatum — der CHECK lässt es nicht anders zu.
|
|
kuendigungsschutz_bis: draft.hasKuendigungsschutz ? draft.kuendigungsschutzBis || null : 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>
|
|
);
|
|
}
|