Show people surname first

Employee names now read "Winkler, Hannah" wherever a person appears in a
list, a table, a heading or a tree node. That is the order a personnel
list is kept in, it is the order people are looked up in, and it finally
matches the sorting — the employee list has always been ordered by
surname, which made an alphabetical page look unsorted.

The name was being assembled inline in about twenty places. A rename
that catches half of them is worse than none, so it now goes through
fmtName in lib/format.ts and every display site calls it.

Sentences keep the natural order: "Hannah Winkler wurde versetzt" reads
like German, "Winkler, Hannah wurde versetzt" reads like a form. So the
toasts are unchanged and only labels moved.

Two things the change would have quietly broken:

The org chart's own filter matched against "first last". It now matches
either order, with or without the comma, so typing what you see works
and so does typing what you remember.

The print model sorted by the last word of the composed name, which
happened to be the surname and is now the first name — every printed
unit would have come out sorted by first name. It sorts on the surname
field itself now, which is what it meant all along.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-14 11:44:03 +02:00
parent a3fac47f47
commit 8a76b3688f
18 changed files with 120 additions and 42 deletions

View File

@@ -9,7 +9,7 @@ import { currentUserId } from "@/lib/auth/session";
import { sql, withUser } from "@/lib/db"; import { sql, withUser } from "@/lib/db";
import { istPersonalnummer, suchMuster } from "@/lib/employee-search"; import { istPersonalnummer, suchMuster } from "@/lib/employee-search";
import { derivedStatusFilter } from "@/lib/employee-status-filter"; import { derivedStatusFilter } from "@/lib/employee-status-filter";
import { fmtDate, todayIso } from "@/lib/format"; import { fmtDate, fmtName, todayIso } from "@/lib/format";
import { breadcrumbLabel, divisionOf, loadOrgMaps, subtreeOf, unitOf } from "@/lib/org"; import { breadcrumbLabel, divisionOf, loadOrgMaps, subtreeOf, unitOf } from "@/lib/org";
import { loadPlacements } from "@/lib/placement"; import { loadPlacements } from "@/lib/placement";
import type { EmploymentStatus } from "@/lib/supabase/types"; import type { EmploymentStatus } from "@/lib/supabase/types";
@@ -240,7 +240,7 @@ export default async function EmployeesPage({ searchParams }: EmployeesPageProps
<Avatar firstName={e.first_name} lastName={e.last_name} /> <Avatar firstName={e.first_name} lastName={e.last_name} />
<div className="min-w-0"> <div className="min-w-0">
<div className="truncate font-semibold text-ink"> <div className="truncate font-semibold text-ink">
{e.first_name} {e.last_name} {fmtName(e.first_name, e.last_name)}
</div> </div>
<div className="truncate text-xs text-ink-muted">{placement?.jobTitle ?? e.job_title}</div> <div className="truncate text-xs text-ink-muted">{placement?.jobTitle ?? e.job_title}</div>
</div> </div>

View File

@@ -3,7 +3,7 @@ import Link from "next/link";
import { DraftsCard } from "@/components/dashboard/DraftsCard"; import { DraftsCard } from "@/components/dashboard/DraftsCard";
import { Card, CARD_CLASS, CardTitle } from "@/components/ui/Card"; import { Card, CARD_CLASS, CardTitle } from "@/components/ui/Card";
import { actionBadgeStyle } from "@/lib/colors"; import { actionBadgeStyle } from "@/lib/colors";
import { addDaysIso, fmtDate, todayIso } from "@/lib/format"; import { addDaysIso, fmtDate, fmtName, todayIso } from "@/lib/format";
import { divisionOf, loadOrgMaps } from "@/lib/org"; import { divisionOf, loadOrgMaps } from "@/lib/org";
import { loadPlacements } from "@/lib/placement"; import { loadPlacements } from "@/lib/placement";
import { loadOpenPositions } from "@/lib/positions"; import { loadOpenPositions } from "@/lib/positions";
@@ -205,19 +205,19 @@ export default async function DashboardPage() {
const upcoming: UpcomingItem[] = [ const upcoming: UpcomingItem[] = [
...(upcomingHires).map((e) => ({ ...(upcomingHires).map((e) => ({
id: e.id, id: e.id,
label: `${e.first_name} ${e.last_name}`, label: fmtName(e.first_name, e.last_name),
date: e.entry_date, date: e.entry_date,
kind: "hire" as const, kind: "hire" as const,
})), })),
...(upcomingExits).map((e) => ({ ...(upcomingExits).map((e) => ({
id: e.id, id: e.id,
label: `${e.first_name} ${e.last_name}`, label: fmtName(e.first_name, e.last_name),
date: e.exit_date!, date: e.exit_date!,
kind: "exit" as const, kind: "exit" as const,
})), })),
...(upcomingReturns).map((e) => ({ ...(upcomingReturns).map((e) => ({
id: e.id, id: e.id,
label: `${e.first_name} ${e.last_name}`, label: fmtName(e.first_name, e.last_name),
date: e.karenz_return_date!, date: e.karenz_return_date!,
kind: "return" as const, kind: "return" as const,
})), })),
@@ -338,7 +338,7 @@ export default async function DashboardPage() {
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT_STYLES[h.event_type] ?? "bg-ink-muted"}`} aria-hidden /> <span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT_STYLES[h.event_type] ?? "bg-ink-muted"}`} aria-hidden />
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-x-2 gap-y-1"> <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
<span className="text-sm font-semibold text-ink">{h.first_name && h.last_name ? `${h.first_name} ${h.last_name}` : "Unbekannt"}</span> <span className="text-sm font-semibold text-ink">{h.first_name && h.last_name ? fmtName(h.first_name, h.last_name) : "Unbekannt"}</span>
<span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${actionBadgeStyle(h.event_type)}`}> <span className={`rounded-full px-2 py-0.5 text-[11px] font-semibold ${actionBadgeStyle(h.event_type)}`}>
{h.event_type} {h.event_type}
</span> </span>

View File

@@ -1,7 +1,7 @@
import { NextResponse, type NextRequest } from "next/server"; import { NextResponse, type NextRequest } from "next/server";
import { statusLabel } from "@/lib/absence"; import { statusLabel } from "@/lib/absence";
import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn } from "@/lib/export"; import { exportFilename, exportResponseHeaders, toCsv, toXlsx, type ExportColumn } from "@/lib/export";
import { todayIso } from "@/lib/format"; import { fmtName, todayIso } from "@/lib/format";
import { subtreeOf } from "@/lib/org"; import { subtreeOf } from "@/lib/org";
import { loadPlacements, loadReportingLineMap } from "@/lib/placement"; import { loadPlacements, loadReportingLineMap } from "@/lib/placement";
import { LEERE_CRITERIA, parseCriteria, passtImSpeicher } from "@/lib/report-criteria"; import { LEERE_CRITERIA, parseCriteria, passtImSpeicher } from "@/lib/report-criteria";
@@ -76,7 +76,7 @@ export async function GET(request: NextRequest) {
} }
); );
const managerName = new Map(allEmployees.map((e) => [e.id, `${e.first_name} ${e.last_name}`])); const managerName = new Map(allEmployees.map((e) => [e.id, fmtName(e.first_name, e.last_name)]));
// Der Einheitenfilter meint den ganzen Teilbaum — sonst enthielte ein // Der Einheitenfilter meint den ganzen Teilbaum — sonst enthielte ein
// Export für "Produktion" nur die Bereichsleitung. // Export für "Produktion" nur die Bereichsleitung.
const allowedUnits = filters.division ? new Set(subtreeOf(orgMaps, filters.division)) : null; const allowedUnits = filters.division ? new Set(subtreeOf(orgMaps, filters.division)) : null;

View File

@@ -9,7 +9,7 @@ import { SegmentedControl } from "@/components/ui/SegmentedControl";
import { SlideOver } from "@/components/ui/SlideOver"; import { SlideOver } from "@/components/ui/SlideOver";
import { useToast } from "@/components/ui/Toast"; import { useToast } from "@/components/ui/Toast";
import { ABSENCE_TYPES, absenceLabel } from "@/lib/absence"; import { ABSENCE_TYPES, absenceLabel } from "@/lib/absence";
import { fmtDate } from "@/lib/format"; import { fmtDate, fmtName } from "@/lib/format";
import type { Database } from "@/lib/supabase/types"; import type { Database } from "@/lib/supabase/types";
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"]; type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
@@ -127,7 +127,7 @@ export function KarenzPanel({ open, onClose, employee }: { open: boolean; onClos
open={open} open={open}
onClose={onClose} onClose={onClose}
title={isOnKarenz ? "Langzeitabwesenheit verwalten" : "Langzeitabwesenheit erfassen"} title={isOnKarenz ? "Langzeitabwesenheit verwalten" : "Langzeitabwesenheit erfassen"}
subtitle={`${employee.first_name} ${employee.last_name} · ${employee.job_title}`} subtitle={`${fmtName(employee.first_name, employee.last_name)} · ${employee.job_title}`}
footer={ footer={
<> <>
<Button variant="ghost" onClick={onClose}> <Button variant="ghost" onClick={onClose}>

View File

@@ -8,6 +8,7 @@ import { SelectField, TextField } from "@/components/ui/Field";
import { SlideOver } from "@/components/ui/SlideOver"; import { SlideOver } from "@/components/ui/SlideOver";
import { useToast } from "@/components/ui/Toast"; import { useToast } from "@/components/ui/Toast";
import type { Database, PaygradeType } from "@/lib/supabase/types"; import type { Database, PaygradeType } from "@/lib/supabase/types";
import { fmtName } from "@/lib/format";
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"]; type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
@@ -55,7 +56,7 @@ export function PromotePanel({ open, onClose, employee }: { open: boolean; onClo
open={open} open={open}
onClose={onClose} onClose={onClose}
title="Beförderung" title="Beförderung"
subtitle={`${employee.first_name} ${employee.last_name} · ${employee.job_title}`} subtitle={`${fmtName(employee.first_name, employee.last_name)} · ${employee.job_title}`}
footer={ footer={
<> <>
<Button variant="ghost" onClick={onClose}> <Button variant="ghost" onClick={onClose}>

View File

@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/Button";
import { SelectField, TextField } from "@/components/ui/Field"; import { SelectField, TextField } from "@/components/ui/Field";
import { SlideOver } from "@/components/ui/SlideOver"; import { SlideOver } from "@/components/ui/SlideOver";
import { useToast } from "@/components/ui/Toast"; import { useToast } from "@/components/ui/Toast";
import { fmtDate } from "@/lib/format"; import { fmtDate, fmtName } from "@/lib/format";
import type { OpenPositionResolved } from "@/lib/positions"; import type { OpenPositionResolved } from "@/lib/positions";
import type { Database } from "@/lib/supabase/types"; import type { Database } from "@/lib/supabase/types";
@@ -87,7 +87,7 @@ export function RehirePanel({
open={open} open={open}
onClose={onClose} onClose={onClose}
title="Wiedereinstellung" title="Wiedereinstellung"
subtitle={`${employee.first_name} ${employee.last_name}`} subtitle={fmtName(employee.first_name, employee.last_name)}
footer={ footer={
<> <>
<Button variant="ghost" onClick={onClose}> <Button variant="ghost" onClick={onClose}>

View File

@@ -8,6 +8,7 @@ import { SelectField, TextField, TextareaField } from "@/components/ui/Field";
import { SlideOver } from "@/components/ui/SlideOver"; import { SlideOver } from "@/components/ui/SlideOver";
import { useToast } from "@/components/ui/Toast"; import { useToast } from "@/components/ui/Toast";
import type { Database } from "@/lib/supabase/types"; import type { Database } from "@/lib/supabase/types";
import { fmtName } from "@/lib/format";
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"]; type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
@@ -52,7 +53,7 @@ export function TerminatePanel({ open, onClose, employee, directReportCount }: T
open={open} open={open}
onClose={onClose} onClose={onClose}
title="Austritt" title="Austritt"
subtitle={`${employee.first_name} ${employee.last_name} · ${employee.job_title}`} subtitle={`${fmtName(employee.first_name, employee.last_name)} · ${employee.job_title}`}
footer={ footer={
<> <>
<Button variant="ghost" onClick={onClose}> <Button variant="ghost" onClick={onClose}>

View File

@@ -9,6 +9,7 @@ import { SlideOver } from "@/components/ui/SlideOver";
import { useToast } from "@/components/ui/Toast"; import { useToast } from "@/components/ui/Toast";
import type { OpenPositionResolved } from "@/lib/positions"; import type { OpenPositionResolved } from "@/lib/positions";
import type { Database } from "@/lib/supabase/types"; import type { Database } from "@/lib/supabase/types";
import { fmtName } from "@/lib/format";
type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"]; type EmployeeRow = Database["public"]["Tables"]["employees"]["Row"];
@@ -68,7 +69,7 @@ export function TransferPanel({ open, onClose, employee, openPositions }: Transf
open={open} open={open}
onClose={onClose} onClose={onClose}
title="Versetzung" title="Versetzung"
subtitle={`${employee.first_name} ${employee.last_name} · ${employee.job_title}`} subtitle={`${fmtName(employee.first_name, employee.last_name)} · ${employee.job_title}`}
footer={ footer={
<> <>
<Button variant="ghost" onClick={onClose}> <Button variant="ghost" onClick={onClose}>

View File

@@ -2,6 +2,7 @@ import { Network } from "lucide-react";
import Link from "next/link"; import Link from "next/link";
import { Avatar } from "@/components/ui/Avatar"; import { Avatar } from "@/components/ui/Avatar";
import { LINK_BUTTON_CLASS } from "@/components/ui/Button"; import { LINK_BUTTON_CLASS } from "@/components/ui/Button";
import { fmtName } from "@/lib/format";
type MiniEmployee = { id: string; first_name: string; last_name: string; job_title: string; status?: string }; type MiniEmployee = { id: string; first_name: string; last_name: string; job_title: string; status?: string };
@@ -37,7 +38,7 @@ export function OrganisationTab({ employeeId, manager, formalManager, directRepo
</h3> </h3>
{formalManager && ( {formalManager && (
<p className="mb-2 text-xs text-ink-muted"> <p className="mb-2 text-xs text-ink-muted">
Zuständig ist {formalManager.first_name} {formalManager.last_name}; während der Abwesenheit übernimmt die nächste Zuständig ist {fmtName(formalManager.first_name, formalManager.last_name)}; während der Abwesenheit übernimmt die nächste
besetzte Ebene. besetzte Ebene.
</p> </p>
)} )}
@@ -46,7 +47,7 @@ export function OrganisationTab({ employeeId, manager, formalManager, directRepo
<Avatar firstName={manager.first_name} lastName={manager.last_name} /> <Avatar firstName={manager.first_name} lastName={manager.last_name} />
<div> <div>
<div className="text-sm font-semibold text-ink"> <div className="text-sm font-semibold text-ink">
{manager.first_name} {manager.last_name} {fmtName(manager.first_name, manager.last_name)}
</div> </div>
<div className="text-xs text-ink-muted">{manager.job_title}</div> <div className="text-xs text-ink-muted">{manager.job_title}</div>
</div> </div>
@@ -65,7 +66,7 @@ export function OrganisationTab({ employeeId, manager, formalManager, directRepo
<Avatar firstName={r.first_name} lastName={r.last_name} /> <Avatar firstName={r.first_name} lastName={r.last_name} />
<div> <div>
<div className="text-sm font-semibold text-ink"> <div className="text-sm font-semibold text-ink">
{r.first_name} {r.last_name} {fmtName(r.first_name, r.last_name)}
</div> </div>
<div className="text-xs text-ink-muted">{r.job_title}</div> <div className="text-xs text-ink-muted">{r.job_title}</div>
</div> </div>

View File

@@ -9,6 +9,7 @@ import { SearchInput } from "@/components/ui/SearchInput";
import { SegmentedControl } from "@/components/ui/SegmentedControl"; import { SegmentedControl } from "@/components/ui/SegmentedControl";
import { LazyGraphOrgChart } from "./LazyGraphOrgChart"; import { LazyGraphOrgChart } from "./LazyGraphOrgChart";
import type { ChartNode, OrgEmployee } from "./types"; import type { ChartNode, OrgEmployee } from "./types";
import { fmtName } from "@/lib/format";
type ViewMode = "list" | "graph"; type ViewMode = "list" | "graph";
@@ -53,7 +54,7 @@ export function EmployeeTree({ employees, focusId = null }: { employees: OrgEmpl
// Both badges name a person by id, so the lookup is shared rather than // Both badges name a person by id, so the lookup is shared rather than
// rebuilt per node. // rebuilt per node.
const nameById = useMemo(() => new Map(employees.map((e) => [e.id, `${e.first_name} ${e.last_name}`])), [employees]); const nameById = useMemo(() => new Map(employees.map((e) => [e.id, fmtName(e.first_name, e.last_name)])), [employees]);
const nameOf = useCallback((id: string | null) => (id ? nameById.get(id) : undefined), [nameById]); const nameOf = useCallback((id: string | null) => (id ? nameById.get(id) : undefined), [nameById]);
const matchIds = useMemo(() => { const matchIds = useMemo(() => {
@@ -64,8 +65,17 @@ export function EmployeeTree({ employees, focusId = null }: { employees: OrgEmpl
const q = query.trim().toLowerCase(); const q = query.trim().toLowerCase();
const matches = new Set<string>(); const matches = new Set<string>();
for (const e of employees) { for (const e of employees) {
// Beide Reihenfolgen: angezeigt wird „Winkler, Hannah", im Kopf hat man
// aber je nach Anlass das eine oder das andere zuerst. Wer abtippt, was
// er sieht, soll ebenso fündig werden wie jemand, der „hannah winkler"
// eingibt.
const vorNach = `${e.first_name} ${e.last_name}`.toLowerCase();
const nachVor = fmtName(e.first_name, e.last_name).toLowerCase();
if ( if (
`${e.first_name} ${e.last_name}`.toLowerCase().includes(q) || vorNach.includes(q) ||
nachVor.includes(q) ||
// Ohne den Beistrich, falls jemand ihn beim Abtippen weglässt.
nachVor.replace(",", "").includes(q) ||
e.job_title.toLowerCase().includes(q) || e.job_title.toLowerCase().includes(q) ||
String(e.personnel_number).includes(q) String(e.personnel_number).includes(q)
) { ) {
@@ -118,7 +128,7 @@ export function EmployeeTree({ employees, focusId = null }: { employees: OrgEmpl
return { return {
id: e.id, id: e.id,
kind: "person", kind: "person",
label: `${e.first_name} ${e.last_name}`, label: fmtName(e.first_name, e.last_name),
sublabel: e.job_title, sublabel: e.job_title,
href: `/employees/${e.id}`, href: `/employees/${e.id}`,
avatar: { firstName: e.first_name, lastName: e.last_name }, avatar: { firstName: e.first_name, lastName: e.last_name },
@@ -159,7 +169,7 @@ export function EmployeeTree({ employees, focusId = null }: { employees: OrgEmpl
<Avatar firstName={e.first_name} lastName={e.last_name} size="sm" /> <Avatar firstName={e.first_name} lastName={e.last_name} size="sm" />
<Link href={`/employees/${e.id}`} className="min-w-0 flex-1 hover:underline"> <Link href={`/employees/${e.id}`} className="min-w-0 flex-1 hover:underline">
<span className="text-sm font-semibold text-ink"> <span className="text-sm font-semibold text-ink">
{e.first_name} {e.last_name} {fmtName(e.first_name, e.last_name)}
</span> </span>
<span className="ml-2 text-xs text-ink-muted">{e.job_title}</span> <span className="ml-2 text-xs text-ink-muted">{e.job_title}</span>
</Link> </Link>

View File

@@ -6,6 +6,7 @@ import { useCallback, useMemo, useState } from "react";
import { SegmentedControl } from "@/components/ui/SegmentedControl"; import { SegmentedControl } from "@/components/ui/SegmentedControl";
import { LazyGraphOrgChart } from "./LazyGraphOrgChart"; import { LazyGraphOrgChart } from "./LazyGraphOrgChart";
import type { ChartNode, OrgEmployee, OrgUnitNode, OrgVacancy } from "./types"; import type { ChartNode, OrgEmployee, OrgUnitNode, OrgVacancy } from "./types";
import { fmtName } from "@/lib/format";
// Die Struktursicht. Sie folgt jetzt org_units.parent_id statt einer fest // Die Struktursicht. Sie folgt jetzt org_units.parent_id statt einer fest
// verdrahteten Abfolge Bereich → Abteilung → Team: eine fünfte Ebene ist // verdrahteten Abfolge Bereich → Abteilung → Team: eine fünfte Ebene ist
@@ -178,7 +179,7 @@ export function buildUnitTree(units: OrgUnitNode[], employees: OrgEmployee[], va
.map((p) => ({ .map((p) => ({
id: p.id, id: p.id,
kind: "person" as const, kind: "person" as const,
label: `${p.first_name} ${p.last_name}`, label: fmtName(p.first_name, p.last_name),
href: `/employees/${p.id}`, href: `/employees/${p.id}`,
avatar: { firstName: p.first_name, lastName: p.last_name }, avatar: { firstName: p.first_name, lastName: p.last_name },
absent: p.absent, absent: p.absent,
@@ -204,7 +205,7 @@ export function buildUnitTree(units: OrgUnitNode[], employees: OrgEmployee[], va
kind: "role", kind: "role",
label: `${unit.org_number} · ${unit.name}`, label: `${unit.org_number} · ${unit.name}`,
sublabel: chief sublabel: chief
? `Leitung: ${chief.first_name} ${chief.last_name}${chief.absent ? " (abwesend)" : ""}` ? `Leitung: ${fmtName(chief.first_name, chief.last_name)}${chief.absent ? " (abwesend)" : ""}`
: "Leitung vakant", : "Leitung vakant",
vacant: !chief, vacant: !chief,
children: [...subUnits, ...titleGroups, ...vacancyNodes], children: [...subUnits, ...titleGroups, ...vacancyNodes],

View File

@@ -56,8 +56,27 @@ export function initials(firstName: string, lastName: string): string {
return `${a}${b}`; return `${a}${b}`;
} }
// "Dr. Max Mustermann, MSc MBA" — prefix titles precede the name, suffix // „Mustermann, Max" — der Nachname zuerst.
// titles follow after a comma, both space-joined in the stored order. //
// So steht es in jeder Personalliste, und danach wird gesucht: wer jemanden
// sucht, hat den Nachnamen im Kopf. Nebenbei stimmt die Anzeige damit auch
// mit der Sortierung überein, die schon immer nach Nachnamen ging — vorher
// las sich eine alphabetische Liste, als wäre sie ungeordnet.
//
// Eine Stelle für alle: der Name wurde an gut zwanzig Orten einzeln
// zusammengesetzt, und eine Umstellung, die die Hälfte davon vergisst, ist
// schlimmer als gar keine.
export function fmtName(firstName: string, lastName: string): string {
const nach = lastName?.trim() ?? "";
const vor = firstName?.trim() ?? "";
if (!nach) return vor;
if (!vor) return nach;
return `${nach}, ${vor}`;
}
// "Mustermann, Dr. Max, MSc MBA" — vorangestellte Titel stehen beim
// Vornamen, nachgestellte am Ende. Der Nachname bleibt vorne, damit auch die
// Überschrift einer Personalakte so beginnt wie ihr Eintrag in der Liste.
export function fmtFullName( export function fmtFullName(
firstName: string, firstName: string,
lastName: string, lastName: string,
@@ -66,7 +85,7 @@ export function fmtFullName(
): string { ): string {
const prefix = titlePrefix && titlePrefix.length > 0 ? `${titlePrefix.join(" ")} ` : ""; const prefix = titlePrefix && titlePrefix.length > 0 ? `${titlePrefix.join(" ")} ` : "";
const suffix = titleSuffix && titleSuffix.length > 0 ? `, ${titleSuffix.join(" ")}` : ""; const suffix = titleSuffix && titleSuffix.length > 0 ? `, ${titleSuffix.join(" ")}` : "";
return `${prefix}${firstName} ${lastName}${suffix}`; return `${fmtName(`${prefix}${firstName}`, lastName)}${suffix}`;
} }
// Whole years between two ISO dates. Compares the "MM-DD" tails as strings, // Whole years between two ISO dates. Compares the "MM-DD" tails as strings,

View File

@@ -1,5 +1,6 @@
import type { Tx } from "./db"; import type { Tx } from "./db";
import type { Database } from "./supabase/types"; import type { Database } from "./supabase/types";
import { fmtName } from "./format";
export type OpenNote = Database["public"]["Tables"]["employee_notes"]["Row"] & { export type OpenNote = Database["public"]["Tables"]["employee_notes"]["Row"] & {
employeeName: string; employeeName: string;
@@ -26,7 +27,7 @@ export async function loadOpenNotes(tx: Tx): Promise<OpenNote[]> {
const { first_name, last_name, ...note } = row; const { first_name, last_name, ...note } = row;
return { return {
...(note as Database["public"]["Tables"]["employee_notes"]["Row"]), ...(note as Database["public"]["Tables"]["employee_notes"]["Row"]),
employeeName: first_name && last_name ? `${first_name} ${last_name}` : "Unbekannt", employeeName: first_name && last_name ? fmtName(first_name, last_name) : "Unbekannt",
}; };
}); });
} }

View File

@@ -1,4 +1,5 @@
import type { OrgEmployee, OrgUnitNode, OrgVacancy } from "@/components/orgchart/types"; import type { OrgEmployee, OrgUnitNode, OrgVacancy } from "@/components/orgchart/types";
import { fmtName } from "@/lib/format";
// Das Modell für den Druck. // Das Modell für den Druck.
// //
@@ -18,6 +19,8 @@ import type { OrgEmployee, OrgUnitNode, OrgVacancy } from "@/components/orgchart
export type PrintPerson = { export type PrintPerson = {
id: string; id: string;
/** Getrennt mitgeführt, weil danach sortiert wird — siehe nachName. */
lastName: string;
name: string; name: string;
jobTitle: string; jobTitle: string;
personnelNumber: number; personnelNumber: number;
@@ -52,7 +55,8 @@ export type PrintModel = {
function personFrom(e: OrgEmployee): PrintPerson { function personFrom(e: OrgEmployee): PrintPerson {
return { return {
id: e.id, id: e.id,
name: `${e.first_name} ${e.last_name}`, lastName: e.last_name,
name: fmtName(e.first_name, e.last_name),
jobTitle: e.job_title, jobTitle: e.job_title,
personnelNumber: e.personnel_number, personnelNumber: e.personnel_number,
isChief: e.is_chief, isChief: e.is_chief,
@@ -61,9 +65,16 @@ function personFrom(e: OrgEmployee): PrintPerson {
}; };
} }
/** Nachname, dann Vorname — wie in jeder Liste, die jemand durchsucht. */ /**
* Nachname, dann Vorname — wie in jeder Liste, die jemand durchsucht.
*
* Der Nachname kommt aus dem eigenen Feld, nicht aus dem zusammengesetzten
* Namen. Vorher wurde das letzte Wort genommen, was bei „Hannah Winkler"
* zufällig stimmte; seit die Anzeige „Winkler, Hannah" lautet, wäre das
* letzte Wort der Vorname, und die Liste stünde nach Vornamen sortiert da.
*/
function nachName(a: PrintPerson, b: PrintPerson): number { function nachName(a: PrintPerson, b: PrintPerson): number {
return a.name.split(" ").slice(-1)[0].localeCompare(b.name.split(" ").slice(-1)[0], "de") || a.name.localeCompare(b.name, "de"); return a.lastName.localeCompare(b.lastName, "de") || a.name.localeCompare(b.name, "de");
} }
export function buildPrintModel( export function buildPrintModel(

View File

@@ -1,5 +1,5 @@
import type { Tx } from "./db"; import type { Tx } from "./db";
import { todayIso } from "./format"; import { fmtName, todayIso } from "./format";
import { breadcrumbLabel, loadOrgMaps, type OrgMaps } from "./org"; import { breadcrumbLabel, loadOrgMaps, type OrgMaps } from "./org";
// Eine offene Stelle ist keine eigene Sache mehr. Sie ist eine Planstelle // Eine offene Stelle ist keine eigene Sache mehr. Sie ist eine Planstelle
@@ -128,7 +128,7 @@ export async function loadOpenPositions(tx: Tx): Promise<OpenPositionResolved[]>
const prev = lastEndByPosition.get(e.position_id); const prev = lastEndByPosition.get(e.position_id);
if (e.valid_to && (!prev || e.valid_to > prev)) lastEndByPosition.set(e.position_id, e.valid_to); if (e.valid_to && (!prev || e.valid_to > prev)) lastEndByPosition.set(e.position_id, e.valid_to);
} }
const chiefNameByUnit = new Map(chiefs.map((c) => [c.org_unit_id, `${c.first_name} ${c.last_name}`])); const chiefNameByUnit = new Map(chiefs.map((c) => [c.org_unit_id, fmtName(c.first_name, c.last_name)]));
return open.map((p) => { return open.map((p) => {
const managerUnit = managerUnitFor(orgMaps, p.org_unit_id, p.is_chief); const managerUnit = managerUnitFor(orgMaps, p.org_unit_id, p.is_chief);

View File

@@ -1,4 +1,4 @@
import { todayIso, yearsBetweenIso } from "./format"; import { fmtName, todayIso, yearsBetweenIso } from "./format";
import type { EmploymentStatus, HistoryEventType, Weekday } from "./supabase/types"; import type { EmploymentStatus, HistoryEventType, Weekday } from "./supabase/types";
export { todayIso }; export { todayIso };
@@ -266,7 +266,7 @@ export function aggregateReport(
const value = measureValue(rowsForGroup, measure, asOf); const value = measureValue(rowsForGroup, measure, asOf);
const people: ReportPerson[] = rowsForGroup.map((e) => ({ const people: ReportPerson[] = rowsForGroup.map((e) => ({
id: e.id, id: e.id,
name: `${e.first_name} ${e.last_name}`, name: fmtName(e.first_name, e.last_name),
title: e.job_title, title: e.job_title,
team: e.org_unit_id ? (lookups.teamName.get(e.org_unit_id) ?? "–") : "–", team: e.org_unit_id ? (lookups.teamName.get(e.org_unit_id) ?? "–") : "–",
entry_date: e.entry_date, entry_date: e.entry_date,
@@ -404,7 +404,7 @@ export function aggregateEvents(
// code working unchanged for both report modes. // code working unchanged for both report modes.
const people: ReportPerson[] = rowsForGroup.map((e) => ({ const people: ReportPerson[] = rowsForGroup.map((e) => ({
id: e.employee_id, id: e.employee_id,
name: `${e.first_name} ${e.last_name}`, name: fmtName(e.first_name, e.last_name),
title: e.description, title: e.description,
team: e.org_unit_id ? (lookups.teamName.get(e.org_unit_id) ?? "–") : "–", team: e.org_unit_id ? (lookups.teamName.get(e.org_unit_id) ?? "–") : "–",
entry_date: e.event_date, entry_date: e.event_date,

View File

@@ -186,11 +186,11 @@ describe("PrintChart", () => {
renderChart(); renderChart();
await zurVorschau(user); await zurVorschau(user);
// Führungskräfte stehen immer im Kasten, gewöhnliche Mitarbeitende nicht. // Führungskräfte stehen immer im Kasten, gewöhnliche Mitarbeitende nicht.
expect(screen.getAllByText("Test Steinbacher").length).toBeGreaterThan(0); expect(screen.getAllByText("Steinbacher, Test").length).toBeGreaterThan(0);
expect(screen.queryByText("Test Aigner")).not.toBeInTheDocument(); expect(screen.queryByText("Aigner, Test")).not.toBeInTheDocument();
await user.click(screen.getByRole("button", { name: /mit Personen/ })); await user.click(screen.getByRole("button", { name: /mit Personen/ }));
expect(screen.getByText("Test Aigner")).toBeInTheDocument(); expect(screen.getByText("Aigner, Test")).toBeInTheDocument();
expect(screen.getByText(/offen · Disposition/)).toBeInTheDocument(); expect(screen.getByText(/offen · Disposition/)).toBeInTheDocument();
// Mit Namen bekommt jede Abteilung ihr eigenes Blatt — ein ganzer Bereich // Mit Namen bekommt jede Abteilung ihr eigenes Blatt — ein ganzer Bereich
// mit allen Namen wäre auf einem Blatt nicht mehr lesbar. // mit allen Namen wäre auf einem Blatt nicht mehr lesbar.
@@ -205,6 +205,6 @@ describe("PrintChart", () => {
// Auf der Produktionsseite: Fertigung und Schicht A stehen ohne Leitung da. // Auf der Produktionsseite: Fertigung und Schicht A stehen ohne Leitung da.
const seite = blaetter()[1]; const seite = blaetter()[1];
expect(within(seite).getAllByText("Leitung unbesetzt")).toHaveLength(2); expect(within(seite).getAllByText("Leitung unbesetzt")).toHaveLength(2);
expect(within(seite).getByText("Test Steinbacher")).toBeInTheDocument(); expect(within(seite).getByText("Steinbacher, Test")).toBeInTheDocument();
}); });
}); });

View File

@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { addDaysIso, daysBetweenIso, fmtAge, fmtDate, initials, tenure, toIsoDate, yearsBetweenIso } from "@/lib/format"; import { addDaysIso, daysBetweenIso, fmtAge, fmtDate, fmtFullName, fmtName, initials, tenure, toIsoDate, yearsBetweenIso } from "@/lib/format";
describe("fmtDate", () => { describe("fmtDate", () => {
it("formats an ISO date string in de-AT order", () => { it("formats an ISO date string in de-AT order", () => {
@@ -125,3 +125,35 @@ describe("toIsoDate", () => {
expect(toIsoDate("2026-03-05T23:30:00Z")).toBe("2026-03-06"); expect(toIsoDate("2026-03-05T23:30:00Z")).toBe("2026-03-06");
}); });
}); });
// Die Anzeige wurde auf „Nachname, Vorname" umgestellt. Das ist die
// Reihenfolge jeder Personalliste, und sie stimmt mit der Sortierung überein,
// die schon immer nach Nachnamen ging.
describe("fmtName", () => {
it("stellt den Nachnamen voran", () => {
expect(fmtName("Hannah", "Winkler")).toBe("Winkler, Hannah");
});
it("kommt ohne Vornamen aus, ohne einen Beistrich stehen zu lassen", () => {
expect(fmtName("", "Winkler")).toBe("Winkler");
expect(fmtName(" ", "Winkler")).toBe("Winkler");
});
it("kommt auch ohne Nachnamen aus", () => {
expect(fmtName("Hannah", "")).toBe("Hannah");
});
it("räumt Leerzeichen an den Rändern weg", () => {
expect(fmtName(" Hannah ", " Winkler ")).toBe("Winkler, Hannah");
});
});
describe("fmtFullName", () => {
it("lässt den Nachnamen vorne und die Titel an ihrem Platz", () => {
expect(fmtFullName("Max", "Mustermann", ["Dr."], ["MSc", "MBA"])).toBe("Mustermann, Dr. Max, MSc MBA");
});
it("verträgt fehlende Titel", () => {
expect(fmtFullName("Max", "Mustermann", [], null)).toBe("Mustermann, Max");
});
});