Phase 5: Positions und Bereiche page with create/staff position modals

This commit is contained in:
2026-07-13 22:43:09 +02:00
parent f91a69147e
commit 80cfaa1e04
9 changed files with 527 additions and 7 deletions

View File

@@ -109,3 +109,23 @@ export async function changeEmployeeData(payload: {
export async function rehireEmployee(payload: { employee_id: string; rehire_date: string }): Promise<ActionResult> {
return callRpc("rehire_employee", payload, [`/employees/${payload.employee_id}`, "/employees", "/"]);
}
export type EmployeeSearchResult = { id: string; first_name: string; last_name: string; job_title: string; team_id: string | null };
// Shared by "Intern besetzen" (staff an open position) and the reorg
// workbench's "Mitarbeiter:in(nen)" multi-select — both search active/
// on-leave employees by name or title.
export async function searchActiveEmployees(query: string): Promise<EmployeeSearchResult[]> {
const supabase = await createClient();
let q = supabase
.from("employees_directory")
.select("id, first_name, last_name, job_title, team_id")
.in("status", ["Aktiv", "Karenz"])
.limit(20);
if (query.trim()) {
const term = query.trim();
q = q.or(`first_name.ilike.%${term}%,last_name.ilike.%${term}%,job_title.ilike.%${term}%`);
}
const { data } = await q;
return data ?? [];
}

View File

@@ -34,3 +34,24 @@ export async function staffPositionInternally(payload: {
revalidatePath("/");
return { success: true };
}
export type SuperiorSearchResult = { id: string; first_name: string; last_name: string; job_title: string; division_id: string };
// For "Position ausschreiben": superior lookup, filtered to team-leads when
// the new position is an IC role, or to division-heads/CEO when the new
// position is itself a team lead (§2).
export async function searchSuperiors(query: string, forLeadPosition: boolean): Promise<SuperiorSearchResult[]> {
const supabase = await createClient();
let q = supabase
.from("employees_directory")
.select("id, first_name, last_name, job_title, division_id")
.eq("status", "Aktiv")
.limit(20);
q = forLeadPosition ? q.lte("org_level", 1) : q.eq("is_lead", true).eq("org_level", 2);
if (query.trim()) {
const term = query.trim();
q = q.or(`first_name.ilike.%${term}%,last_name.ilike.%${term}%,job_title.ilike.%${term}%`);
}
const { data } = await q;
return data ?? [];
}

View File

@@ -0,0 +1,73 @@
import { PositionsPageClient } from "@/components/positions/PositionsPageClient";
import { daysBetween } from "@/lib/format";
import { loadOpenPositions } from "@/lib/positions";
import { createClient } from "@/lib/supabase/server";
export default async function PositionsPage() {
const supabase = await createClient();
const [openPositions, { data: divisions }, { data: departments }, { data: teams }, { data: activeEmployees }, { data: leads }] =
await Promise.all([
loadOpenPositions(supabase),
supabase.from("divisions").select("*").order("name"),
supabase.from("departments").select("*"),
supabase.from("teams").select("*"),
supabase.from("employees_directory").select("team_id, division_id, weekly_hours").in("status", ["Aktiv", "Karenz"]),
supabase
.from("employees_directory")
.select("id, first_name, last_name, team_id, division_id, org_level, is_lead")
.eq("status", "Aktiv")
.or("is_lead.eq.true,org_level.eq.0"),
]);
const teamStats = new Map<string, { headcount: number; fte: number }>();
const divisionHeadcount = new Map<string, number>();
for (const e of activeEmployees ?? []) {
if (e.team_id) {
const s = teamStats.get(e.team_id) ?? { headcount: 0, fte: 0 };
s.headcount += 1;
s.fte += Number(e.weekly_hours) / 38.5;
teamStats.set(e.team_id, s);
}
if (e.division_id) {
divisionHeadcount.set(e.division_id, (divisionHeadcount.get(e.division_id) ?? 0) + 1);
}
}
const divisionHeadByDivision = new Map<string, { id: string; name: string }>();
const teamLeadByTeam = new Map<string, { id: string; name: string }>();
for (const p of leads ?? []) {
const name = `${p.first_name} ${p.last_name}`;
if (p.org_level === 1 && p.division_id) divisionHeadByDivision.set(p.division_id, { id: p.id, name });
if (p.is_lead && p.team_id) teamLeadByTeam.set(p.team_id, { id: p.id, name });
}
const openPositionCountByTeam = new Map<string, number>();
for (const pos of openPositions) {
openPositionCountByTeam.set(pos.team_id, (openPositionCountByTeam.get(pos.team_id) ?? 0) + 1);
}
const divisionCards = (divisions ?? []).map((div) => ({
...div,
head: divisionHeadByDivision.get(div.id) ?? null,
headcount: divisionHeadcount.get(div.id) ?? 0,
departments: (departments ?? [])
.filter((d) => d.division_id === div.id)
.map((dept) => ({
...dept,
teams: (teams ?? [])
.filter((t) => t.department_id === dept.id)
.map((t) => ({
...t,
lead: teamLeadByTeam.get(t.id) ?? null,
headcount: teamStats.get(t.id)?.headcount ?? 0,
fte: teamStats.get(t.id)?.fte ?? 0,
openCount: openPositionCountByTeam.get(t.id) ?? 0,
})),
})),
}));
const openPositionsWithDays = openPositions.map((p) => ({ ...p, daysOpen: daysBetween(p.created_at) }));
return <PositionsPageClient openPositions={openPositionsWithDays} divisionCards={divisionCards} teams={teams ?? []} />;
}

View File

@@ -45,7 +45,7 @@ export function DraftsCard({ drafts }: { drafts: Draft[] }) {
<span className="ml-2 text-xs text-ink-muted">Gespeichert am {fmtDate(d.updated_at)}</span>
</div>
<div className="flex items-center gap-3">
<button type="button" onClick={() => openWizard(d.id)} className="text-xs font-semibold text-brand-700 hover:underline">
<button type="button" onClick={() => openWizard({ draftId: d.id })} className="text-xs font-semibold text-brand-700 hover:underline">
Fortsetzen
</button>
<button

View File

@@ -21,9 +21,10 @@ type HireWizardProps = {
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 }: HireWizardProps) {
export function HireWizard({ open, onClose, openPositions, locations, resumeDraft, initialPositionId }: HireWizardProps) {
const { showToast } = useToast();
const router = useRouter();
const [step, setStep] = useState(0);
@@ -38,11 +39,11 @@ export function HireWizard({ open, onClose, openPositions, locations, resumeDraf
setStep(resumeDraft.step);
setDraftId(resumeDraft.id);
} else {
setDraft(EMPTY_HIRE_DRAFT);
setDraft({ ...EMPTY_HIRE_DRAFT, positionId: initialPositionId ?? "" });
setStep(0);
setDraftId(undefined);
}
}, [open, resumeDraft]);
}, [open, resumeDraft, initialPositionId]);
const selectedPosition = useMemo(
() => openPositions.find((p) => p.id === draft.positionId) ?? null,

View File

@@ -7,8 +7,10 @@ import { HireWizard } from "./HireWizard";
type Location = { id: string; name: string; country: string };
type HireDraft = { id: string; step: number; payload: Record<string, unknown> };
type OpenWizardOptions = { draftId?: string; positionId?: string };
type HireWizardContextValue = {
openWizard: (draftId?: string) => void;
openWizard: (options?: OpenWizardOptions) => void;
};
const HireWizardContext = createContext<HireWizardContextValue | null>(null);
@@ -26,9 +28,11 @@ export function HireWizardProvider({
}) {
const [open, setOpen] = useState(false);
const [resumeDraft, setResumeDraft] = useState<HireDraft | null>(null);
const [initialPositionId, setInitialPositionId] = useState<string | undefined>(undefined);
function openWizard(draftId?: string) {
setResumeDraft(draftId ? (drafts.find((d) => d.id === draftId) ?? null) : null);
function openWizard(options?: OpenWizardOptions) {
setResumeDraft(options?.draftId ? (drafts.find((d) => d.id === options.draftId) ?? null) : null);
setInitialPositionId(options?.positionId);
setOpen(true);
}
@@ -41,6 +45,7 @@ export function HireWizardProvider({
openPositions={openPositions}
locations={locations}
resumeDraft={resumeDraft}
initialPositionId={initialPositionId}
/>
</HireWizardContext.Provider>
);

View File

@@ -0,0 +1,136 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { createPosition, searchSuperiors, type SuperiorSearchResult } from "@/actions/positions";
import { Lookup } from "@/components/ui/Lookup";
import { Modal } from "@/components/ui/Modal";
import { useToast } from "@/components/ui/Toast";
import type { Database } from "@/lib/supabase/types";
type Team = Database["public"]["Tables"]["teams"]["Row"];
export function CreatePositionModal({ open, onClose, teams }: { open: boolean; onClose: () => void; teams: Team[] }) {
const { showToast } = useToast();
const router = useRouter();
const [title, setTitle] = useState("");
const [isLead, setIsLead] = useState(false);
const [superior, setSuperior] = useState<SuperiorSearchResult | null>(null);
const [teamId, setTeamId] = useState("");
const [pending, setPending] = useState(false);
function reset() {
setTitle("");
setIsLead(false);
setSuperior(null);
setTeamId("");
}
async function handleSubmit() {
if (!title || !superior || (isLead && !teamId)) {
showToast("Bitte alle Pflichtfelder ausfüllen.", "error");
return;
}
setPending(true);
const result = await createPosition({
title,
superior_employee_id: superior.id,
is_lead: isLead,
team_id: isLead ? teamId : undefined,
});
setPending(false);
if (result.success) {
showToast("Position ausgeschrieben.");
router.refresh();
onClose();
reset();
} else {
showToast(result.error ?? "Fehler beim Anlegen.", "error");
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Position ausschreiben"
footer={
<>
<button onClick={onClose} className="rounded px-4 py-2 text-sm font-semibold text-ink-body hover:bg-surface">
Abbrechen
</button>
<button
onClick={handleSubmit}
disabled={pending}
className="rounded bg-brand-500 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
>
Ausschreiben
</button>
</>
}
>
<div className="flex flex-col gap-4">
<div>
<label className="mb-1 block text-sm font-semibold text-ink">Titel*</label>
<input value={title} onChange={(e) => setTitle(e.target.value)} className="w-full rounded border border-border px-3 py-2 text-sm" />
</div>
<label className="flex items-center gap-2 text-sm text-ink-body">
<input
type="checkbox"
checked={isLead}
onChange={(e) => {
setIsLead(e.target.checked);
setSuperior(null);
}}
/>
Führungsposition (Teamleitung)
</label>
<div>
<label className="mb-1 block text-sm font-semibold text-ink">
{isLead ? "Übergeordnete Bereichsleitung*" : "Übergeordnete Teamleitung*"}
</label>
{!superior ? (
<Lookup<SuperiorSearchResult>
placeholder="Name oder Titel…"
onSearch={(q) => searchSuperiors(q, isLead)}
onSelect={setSuperior}
renderResult={(p) => (
<div>
<div className="font-semibold text-ink">
{p.first_name} {p.last_name}
</div>
<div className="text-xs text-ink-muted">{p.job_title}</div>
</div>
)}
/>
) : (
<div className="flex items-center justify-between rounded border border-border bg-surface p-3">
<div>
<div className="text-sm font-semibold text-ink">
{superior.first_name} {superior.last_name}
</div>
<div className="text-xs text-ink-muted">{superior.job_title}</div>
</div>
<button type="button" onClick={() => setSuperior(null)} className="text-xs text-ink-muted hover:text-ink">
Ändern
</button>
</div>
)}
</div>
{isLead && (
<div>
<label className="mb-1 block text-sm font-semibold text-ink">Zu leitendes Team*</label>
<select value={teamId} onChange={(e) => setTeamId(e.target.value)} className="w-full rounded border border-border px-3 py-2 text-sm">
<option value="">Bitte wählen</option>
{teams.map((t) => (
<option key={t.id} value={t.id}>
{t.name}
</option>
))}
</select>
</div>
)}
</div>
</Modal>
);
}

View File

@@ -0,0 +1,162 @@
"use client";
import { Plus } from "lucide-react";
import Link from "next/link";
import { useState } from "react";
import { useHireWizard } from "@/components/hire/HireWizardContext";
import type { OpenPositionResolved } from "@/lib/positions";
import { CreatePositionModal } from "./CreatePositionModal";
import { StaffInternallyModal } from "./StaffInternallyModal";
type Team = {
id: string;
org_number: string;
name: string;
lead: { id: string; name: string } | null;
headcount: number;
fte: number;
openCount: number;
};
type Department = { id: string; org_number: string; name: string; teams: Team[] };
type DivisionCard = {
id: string;
org_number: string;
name: string;
head: { id: string; name: string } | null;
headcount: number;
departments: Department[];
};
type OpenPositionWithDays = OpenPositionResolved & { daysOpen: number };
type PositionsPageClientProps = {
openPositions: OpenPositionWithDays[];
divisionCards: DivisionCard[];
teams: { id: string; org_number: string; name: string; department_id: string }[];
};
export function PositionsPageClient({ openPositions, divisionCards, teams }: PositionsPageClientProps) {
const { openWizard } = useHireWizard();
const [createOpen, setCreateOpen] = useState(false);
const [staffTarget, setStaffTarget] = useState<{ id: string; title: string; is_lead: boolean } | null>(null);
return (
<div className="flex flex-col gap-6">
<div className="rounded border border-border bg-white p-4">
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-bold text-ink">Offene Positionen ({openPositions.length})</h2>
<button
type="button"
onClick={() => setCreateOpen(true)}
className="flex items-center gap-1.5 rounded bg-brand-500 px-3 py-1.5 text-sm font-semibold text-white hover:bg-brand-600"
>
<Plus className="h-4 w-4" />
Position ausschreiben
</button>
</div>
{openPositions.length === 0 ? (
<p className="text-sm text-ink-muted">Derzeit keine offenen Positionen.</p>
) : (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{openPositions.map((p) => (
<div key={p.id} className="rounded border border-border p-3">
<div className="text-sm font-semibold text-ink">{p.title}</div>
<div className="text-xs text-ink-muted">
{p.position_number} · {p.orgLabel}
</div>
<div className="mt-1 text-xs text-ink-muted">seit {p.daysOpen} Tagen offen</div>
<div className="mt-3 flex gap-2">
<button
type="button"
onClick={() => setStaffTarget({ id: p.id, title: p.title, is_lead: p.is_lead })}
className="flex-1 rounded bg-brand-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-600"
>
Intern
</button>
<button
type="button"
onClick={() => openWizard({ positionId: p.id })}
className="flex-1 rounded border border-border px-3 py-1.5 text-xs font-semibold text-ink-body hover:bg-surface"
>
Extern
</button>
</div>
</div>
))}
</div>
)}
</div>
{divisionCards.map((div) => (
<div key={div.id} className="rounded border border-border bg-white p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-2 border-b border-border pb-3">
<div>
<div className="text-xs text-ink-muted">{div.org_number}</div>
<div className="text-sm font-bold text-ink">{div.name}</div>
{div.head && (
<Link href={`/employees/${div.head.id}`} className="text-xs text-brand-700 hover:underline">
{div.head.name}
</Link>
)}
</div>
<div className="text-sm font-semibold text-ink">{div.headcount} Mitarbeiter:innen</div>
</div>
<div className="flex flex-col gap-4">
{div.departments.map((dept) => (
<div key={dept.id}>
<div className="mb-2 text-xs font-semibold uppercase tracking-wide text-ink-muted">
{dept.org_number} · {dept.name}
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[600px] text-sm">
<thead>
<tr className="text-left text-xs text-ink-muted">
<th className="py-1 pr-3">Team</th>
<th className="py-1 pr-3">Teamleitung</th>
<th className="py-1 pr-3">Headcount</th>
<th className="py-1 pr-3">FTE</th>
<th className="py-1 pr-3">Offen</th>
</tr>
</thead>
<tbody>
{dept.teams.map((team) => (
<tr key={team.id} className="border-t border-border">
<td className="py-1.5 pr-3">
<div className="text-ink">{team.name}</div>
<div className="text-xs text-ink-muted">{team.org_number}</div>
</td>
<td className="py-1.5 pr-3 text-ink-body">
{team.lead ? (
<Link href={`/employees/${team.lead.id}`} className="hover:text-brand-700 hover:underline">
{team.lead.name}
</Link>
) : (
""
)}
</td>
<td className="py-1.5 pr-3 text-ink-body">{team.headcount}</td>
<td className="py-1.5 pr-3 text-ink-body">{team.fte.toFixed(1)}</td>
<td className="py-1.5 pr-3 font-semibold text-brand-700">{team.openCount || ""}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
))}
</div>
</div>
))}
<CreatePositionModal open={createOpen} onClose={() => setCreateOpen(false)} teams={teams} />
{staffTarget && (
<StaffInternallyModal
open={Boolean(staffTarget)}
onClose={() => setStaffTarget(null)}
positionId={staffTarget.id}
positionTitle={staffTarget.title}
isLead={staffTarget.is_lead}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,102 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { searchActiveEmployees, type EmployeeSearchResult } from "@/actions/employees";
import { staffPositionInternally } from "@/actions/positions";
import { Lookup } from "@/components/ui/Lookup";
import { Modal } from "@/components/ui/Modal";
import { useToast } from "@/components/ui/Toast";
type StaffInternallyModalProps = {
open: boolean;
onClose: () => void;
positionId: string;
positionTitle: string;
isLead: boolean;
};
export function StaffInternallyModal({ open, onClose, positionId, positionTitle, isLead }: StaffInternallyModalProps) {
const { showToast } = useToast();
const router = useRouter();
const [employee, setEmployee] = useState<EmployeeSearchResult | null>(null);
const [pending, setPending] = useState(false);
async function handleSubmit() {
if (!employee) return;
setPending(true);
const result = await staffPositionInternally({ position_id: positionId, employee_id: employee.id });
setPending(false);
if (result.success) {
showToast(`${employee.first_name} ${employee.last_name} wurde intern besetzt.`);
router.refresh();
onClose();
setEmployee(null);
} else {
showToast(result.error ?? "Fehler beim Besetzen.", "error");
}
}
return (
<Modal
open={open}
onClose={onClose}
title="Intern besetzen"
footer={
<>
<button onClick={onClose} className="rounded px-4 py-2 text-sm font-semibold text-ink-body hover:bg-surface">
Abbrechen
</button>
<button
onClick={handleSubmit}
disabled={pending || !employee}
className="rounded bg-brand-500 px-4 py-2 text-sm font-semibold text-white disabled:opacity-50"
>
Besetzen
</button>
</>
}
>
<div className="flex flex-col gap-4">
<p className="text-sm text-ink-body">
Position: <span className="font-semibold">{positionTitle}</span>
</p>
{isLead && (
<div className="rounded bg-warning-bg px-3 py-2 text-sm text-warning-text">
Dies ist eine Führungsposition: Das gesamte Team wird der ausgewählten Person unterstellt.
</div>
)}
<div>
<label className="mb-1 block text-sm font-semibold text-ink">Mitarbeiter:in*</label>
{!employee ? (
<Lookup<EmployeeSearchResult>
placeholder="Name oder Titel…"
onSearch={searchActiveEmployees}
onSelect={setEmployee}
renderResult={(e) => (
<div>
<div className="font-semibold text-ink">
{e.first_name} {e.last_name}
</div>
<div className="text-xs text-ink-muted">{e.job_title}</div>
</div>
)}
/>
) : (
<div className="flex items-center justify-between rounded border border-border bg-surface p-3">
<div>
<div className="text-sm font-semibold text-ink">
{employee.first_name} {employee.last_name}
</div>
<div className="text-xs text-ink-muted">{employee.job_title}</div>
</div>
<button type="button" onClick={() => setEmployee(null)} className="text-xs text-ink-muted hover:text-ink">
Ändern
</button>
</div>
)}
</div>
</div>
</Modal>
);
}