Dieser Commit ist enthalten in:
Claude Project Manager
2025-10-16 08:24:01 +02:00
Ursprung 01d0988515
Commit 4d509d255f
51 geänderte Dateien mit 5922 neuen und 1502 gelöschten Zeilen

Datei-Diff unterdrückt, da er zu groß ist Diff laden

Datei anzeigen

@ -10,11 +10,11 @@
"preview": "vite preview"
},
"dependencies": {
"@react-three/drei": "^9.88.0",
"@react-three/drei": "^9.112.5",
"@react-three/fiber": "^8.15.0",
"@skillmate/shared": "file:../shared",
"@types/three": "^0.180.0",
"axios": "^1.6.2",
"axios": "^1.7.9",
"lucide-react": "^0.542.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@ -31,5 +31,9 @@
"tailwindcss": "^3.3.6",
"typescript": "^5.3.0",
"vite": "^5.0.7"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.52.3",
"@rollup/rollup-win32-x64-msvc": "^4.52.3"
}
}

Datei anzeigen

@ -1,18 +1,28 @@
import { useState, useEffect } from 'react'
import api from '../services/api'
import type { DeputyAssignment, Employee } from '@skillmate/shared'
import type { Employee } from '@skillmate/shared'
import { useAuthStore } from '../stores/authStore'
interface UnitOption {
id: string
name: string
code?: string | null
isPrimary?: boolean
}
export default function DeputyManagement() {
const [asPrincipal, setAsPrincipal] = useState<any[]>([])
const [asDeputy, setAsDeputy] = useState<any[]>([])
const [availableEmployees, setAvailableEmployees] = useState<Employee[]>([])
const [unitOptions, setUnitOptions] = useState<UnitOption[]>([])
const [showAddDialog, setShowAddDialog] = useState(false)
const [loading, setLoading] = useState(true)
const [submitting, setSubmitting] = useState(false)
const [formError, setFormError] = useState('')
const [formData, setFormData] = useState({
deputyId: '',
validFrom: new Date().toISOString().split('T')[0],
validUntil: '',
validUntil: new Date().toISOString().split('T')[0],
reason: '',
canDelegate: true,
unitId: ''
@ -22,6 +32,7 @@ export default function DeputyManagement() {
useEffect(() => {
loadDeputies()
loadEmployees()
loadUnits()
}, [])
const loadDeputies = async () => {
@ -43,28 +54,66 @@ export default function DeputyManagement() {
try {
const response = await api.get('/employees/public')
if (response.data.success) {
setAvailableEmployees(response.data.data)
const sorted = (response.data.data as Employee[])
.filter(emp => emp.id !== user?.employeeId)
.sort((a, b) => `${a.lastName} ${a.firstName}`.localeCompare(`${b.lastName} ${b.firstName}`))
setAvailableEmployees(sorted)
}
} catch (error) {
console.error('Failed to load employees:', error)
}
}
const handleAddDeputy = async () => {
const loadUnits = async () => {
try {
const response = await api.post('/organization/deputies/my', {
...formData,
validFrom: new Date(formData.validFrom).toISOString(),
validUntil: formData.validUntil ? new Date(formData.validUntil).toISOString() : null
})
const response = await api.get('/organization/my-units')
if (response.data.success) {
setUnitOptions(response.data.data || [])
}
} catch (error) {
console.warn('Failed to load organizational units for deputy dialog:', error)
}
}
const handleAddDeputy = async () => {
if (submitting) return
setFormError('')
if (!formData.deputyId) {
setFormError('Bitte wählen Sie eine Vertretung aus.')
return
}
try {
setSubmitting(true)
const payload: any = {
deputyId: formData.deputyId,
validFrom: formData.validFrom,
validUntil: formData.validUntil,
reason: formData.reason || null,
canDelegate: formData.canDelegate
}
if (formData.unitId) {
payload.unitId = formData.unitId
}
const response = await api.post('/organization/deputies/my', payload)
if (response.data.success) {
await loadDeputies()
setShowAddDialog(false)
resetForm()
} else {
setFormError(response.data?.error?.message || 'Vertretung konnte nicht gespeichert werden.')
}
} catch (error) {
} catch (error: any) {
console.error('Failed to add deputy:', error)
const message = error?.response?.data?.error?.message || 'Vertretung konnte nicht gespeichert werden.'
setFormError(message)
} finally {
setSubmitting(false)
}
}
@ -104,14 +153,48 @@ export default function DeputyManagement() {
}
const resetForm = () => {
const today = new Date().toISOString().split('T')[0]
setFormData({
deputyId: '',
validFrom: new Date().toISOString().split('T')[0],
validUntil: '',
validFrom: today,
validUntil: today,
reason: '',
canDelegate: true,
unitId: ''
})
setFormError('')
setSubmitting(false)
}
const openAddDialog = () => {
setFormError('')
const today = new Date().toISOString().split('T')[0]
if (asPrincipal.length > 0) {
const existing = asPrincipal[0]
const existingFrom = existing.validFrom ? existing.validFrom.slice(0, 10) : today
const existingUntil = existing.validUntil ? existing.validUntil.slice(0, 10) : today
setFormData({
deputyId: existing.deputyId || existing.id || '',
validFrom: existingFrom,
validUntil: existingUntil < existingFrom ? existingFrom : existingUntil,
reason: existing.reason || '',
canDelegate: existing.canDelegate === 1 || existing.canDelegate === true,
unitId: existing.unitId || ''
})
} else {
setFormData({
deputyId: '',
validFrom: today,
validUntil: today,
reason: '',
canDelegate: true,
unitId: ''
})
}
setShowAddDialog(true)
}
if (loading) {
@ -132,10 +215,10 @@ export default function DeputyManagement() {
<div className="flex justify-between items-center mb-4">
<h3 className="text-lg font-semibold dark:text-white">Aktuelle Vertretungen</h3>
<button
onClick={() => setShowAddDialog(true)}
onClick={openAddDialog}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
>
+ Vertretung hinzufügen
{asPrincipal.length > 0 ? 'Vertretungszeitraum anpassen' : '+ Vertretung hinzufügen'}
</button>
</div>
@ -213,6 +296,7 @@ export default function DeputyManagement() {
onChange={(e) => setFormData({ ...formData, deputyId: e.target.value })}
className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
required
disabled={asPrincipal.length > 0}
>
<option value="">Bitte wählen...</option>
{availableEmployees.map(emp => (
@ -221,8 +305,33 @@ export default function DeputyManagement() {
</option>
))}
</select>
{asPrincipal.length > 0 && (
<p className="mt-1 text-xs text-gray-500 dark:text-gray-400">
Hinweis: Es kann nur eine Vertretung gepflegt werden. Passen Sie die Zeiträume nach Bedarf an.
</p>
)}
</div>
{unitOptions.length > 0 && (
<div>
<label className="block text-sm font-medium mb-1 dark:text-gray-300">
Für Organisationseinheit (optional)
</label>
<select
value={formData.unitId}
onChange={(e) => setFormData({ ...formData, unitId: e.target.value })}
className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
>
<option value="">Alle Aufgaben / gesamt</option>
{unitOptions.map(unit => (
<option key={unit.id} value={unit.id}>
{unit.name}{unit.code ? ` (${unit.code})` : ''}
</option>
))}
</select>
</div>
)}
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium mb-1 dark:text-gray-300">
@ -231,20 +340,29 @@ export default function DeputyManagement() {
<input
type="date"
value={formData.validFrom}
onChange={(e) => setFormData({ ...formData, validFrom: e.target.value })}
onChange={(e) => {
const value = e.target.value
setFormData(prev => ({
...prev,
validFrom: value,
validUntil: prev.validUntil < value ? value : prev.validUntil
}))
}}
className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
required
/>
</div>
<div>
<label className="block text-sm font-medium mb-1 dark:text-gray-300">
Bis (optional)
Bis *
</label>
<input
type="date"
value={formData.validUntil}
onChange={(e) => setFormData({ ...formData, validUntil: e.target.value })}
className="w-full px-3 py-2 border rounded dark:bg-gray-700 dark:border-gray-600"
required
min={formData.validFrom}
/>
</div>
</div>
@ -282,6 +400,12 @@ export default function DeputyManagement() {
</div>
</div>
{formError && (
<div className="mt-4 rounded-input border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700 dark:border-red-500 dark:bg-red-900/30 dark:text-red-200">
{formError}
</div>
)}
<div className="flex justify-end gap-2 mt-6">
<button
onClick={() => {
@ -294,9 +418,10 @@ export default function DeputyManagement() {
</button>
<button
onClick={handleAddDeputy}
className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
disabled={submitting}
className={`px-4 py-2 rounded text-white ${submitting ? 'bg-blue-400 cursor-wait' : 'bg-blue-600 hover:bg-blue-700'}`}
>
Hinzufügen
{submitting ? 'Speichere...' : 'Hinzufügen'}
</button>
</div>
</div>

Datei anzeigen

@ -1,11 +1,13 @@
import type { Employee } from '@skillmate/shared'
import { formatDepartmentWithDescription, normalizeDepartment } from '../utils/text'
interface EmployeeCardProps {
employee: Employee
onClick: () => void
onDeputyNavigate?: (id: string) => void
}
export default function EmployeeCard({ employee, onClick }: EmployeeCardProps) {
export default function EmployeeCard({ employee, onClick, onDeputyNavigate }: EmployeeCardProps) {
const API_BASE = (import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api'
const PUBLIC_BASE = (import.meta as any).env?.VITE_API_PUBLIC_URL || API_BASE.replace(/\/api$/, '')
const photoSrc = employee.photo && employee.photo.startsWith('/uploads/')
@ -27,9 +29,35 @@ export default function EmployeeCard({ employee, onClick }: EmployeeCardProps) {
}
const availability = getAvailabilityBadge(employee.availability)
const specializations = employee.specializations || []
const currentDeputies = employee.currentDeputies || []
const represents = employee.represents || []
const isUnavailable = employee.availability && employee.availability !== 'available'
const cardHighlightClasses = isUnavailable
? 'border-red-300 bg-red-50 hover:border-red-400 hover:bg-red-50/90 dark:bg-red-900/20 dark:border-red-700 dark:hover:bg-red-900/30'
: ''
const departmentInfo = formatDepartmentWithDescription(employee.department, employee.departmentDescription)
const departmentDescriptionText = normalizeDepartment(departmentInfo.description)
const departmentTasks = normalizeDepartment(employee.departmentTasks || departmentInfo.tasks)
const showDepartmentDescription = departmentDescriptionText.length > 0 && departmentDescriptionText !== departmentTasks
// Show only the end unit; provide full chain as tooltip. Hide top-level root (e.g. DIR/LKA NRW)
const fullPath = normalizeDepartment(departmentInfo.label)
const splitPath = (fullPath || '').split(' -> ').map(s => s.trim()).filter(Boolean)
const filteredPath = splitPath.length > 0 && (/^dir$/i.test(splitPath[0]) || /^lka\s+nrw$/i.test(splitPath[0]))
? splitPath.slice(1)
: splitPath
const shortDepartmentLabel = filteredPath.length > 0 ? filteredPath[filteredPath.length - 1] : (fullPath || '')
const chainTitle = filteredPath.join(' → ') || fullPath
const handleDeputyClick = (event: React.MouseEvent<HTMLButtonElement>, targetId: string) => {
event.stopPropagation()
if (onDeputyNavigate) {
onDeputyNavigate(targetId)
}
}
return (
<div className="card" onClick={onClick}>
<div className={`card ${cardHighlightClasses}`} onClick={onClick}>
<div className="flex items-start justify-between mb-4">
<div className="flex items-center space-x-4">
<div className="w-16 h-16 rounded-full bg-bg-accent dark:bg-dark-primary flex items-center justify-center overflow-hidden">
@ -69,27 +97,100 @@ export default function EmployeeCard({ employee, onClick }: EmployeeCardProps) {
</p>
)}
<p className="text-body text-secondary">
<span className="font-medium">Dienststelle:</span> {employee.department}
<span className="font-medium">Dienststelle:</span>{' '}
<span title={chainTitle}>{shortDepartmentLabel}</span>
</p>
{showDepartmentDescription && (
<p className="text-small text-tertiary ml-4">{departmentDescriptionText}</p>
)}
{departmentTasks && (
<p className="text-small text-secondary">
<span className="font-medium">Aufgaben der Dienststelle:</span> {departmentTasks}
</p>
)}
</div>
{employee.specializations.length > 0 && (
{specializations.length > 0 && (
<div>
<p className="text-small font-medium text-tertiary mb-2">Spezialisierungen:</p>
<div className="flex flex-wrap gap-2">
{employee.specializations.slice(0, 3).map((spec, index) => (
{specializations.slice(0, 3).map((spec, index) => (
<span key={index} className="badge badge-info text-xs">
{spec}
</span>
))}
{employee.specializations.length > 3 && (
{specializations.length > 3 && (
<span className="text-xs text-tertiary">
+{employee.specializations.length - 3} weitere
+{specializations.length - 3} weitere
</span>
)}
</div>
</div>
)}
{represents.length > 0 && (
<div className="mt-2">
<p className="text-small font-medium text-primary">Vertritt</p>
<div className="flex flex-wrap gap-2">
{represents.map(item => {
const label = `${item.firstName || ''} ${item.lastName || ''}`.trim()
const descParts = [
label,
item.position || undefined,
item.availability ? `Status: ${item.availability}` : undefined
].filter(Boolean)
return (
<button
key={item.assignmentId || item.id}
type="button"
title={descParts.join(' · ')}
onClick={(event) => handleDeputyClick(event, item.id)}
className="inline-flex items-center gap-1 rounded-badge bg-blue-100 px-3 py-1 text-sm font-medium text-blue-700 transition hover:bg-blue-200 focus:outline-none focus:ring-2 focus:ring-blue-400 dark:bg-blue-900/40 dark:text-blue-200 dark:hover:bg-blue-900/60"
>
{label || 'Unbekannt'}
{item.position && <span className="text-xs text-blue-500 dark:text-blue-300">({item.position})</span>}
</button>
)
})}
</div>
</div>
)}
{isUnavailable && (
<div className="mt-4">
<p className="text-small font-medium text-red-700 dark:text-red-200 mb-2">Vertretung</p>
{currentDeputies.length > 0 ? (
<div className="flex flex-wrap gap-2">
{currentDeputies.map((deputy) => {
const label = `${deputy.firstName || ''} ${deputy.lastName || ''}`.trim()
const titleParts = [
label,
deputy.position || undefined,
deputy.availability ? `Status: ${deputy.availability}` : undefined,
].filter(Boolean)
return (
<button
key={`${deputy.assignmentId || deputy.id}`}
type="button"
title={titleParts.join(' · ')}
onClick={(event) => handleDeputyClick(event, deputy.id)}
className="inline-flex items-center gap-1 rounded-badge bg-red-100 px-3 py-1 text-sm font-medium text-red-700 transition hover:bg-red-200 focus:outline-none focus:ring-2 focus:ring-red-400 dark:bg-red-900/40 dark:text-red-200 dark:hover:bg-red-900/60"
>
{label || 'Ohne Namen'}
{deputy.position && <span className="text-xs text-red-500 dark:text-red-300">({deputy.position})</span>}
</button>
)
})}
</div>
) : (
<p className="text-small text-red-600 dark:text-red-300">
Keine Vertretung hinterlegt.
</p>
)}
</div>
)}
</div>
)
}

Datei anzeigen

@ -2,6 +2,7 @@ import { useEffect, useState, useCallback } from 'react'
import type { OrganizationalUnit, EmployeeUnitAssignment } from '@skillmate/shared'
import api from '../services/api'
import { useAuthStore } from '../stores/authStore'
import { decodeHtmlEntities } from '../utils/text'
interface OrganizationChartProps {
onClose: () => void
@ -113,6 +114,26 @@ export default function OrganizationChart({ onClose }: OrganizationChartProps) {
return colors[level % colors.length]
}
const getUnitDisplayLabel = (unit?: OrganizationalUnit | null) => {
if (!unit) return ''
const code = unit.code?.trim()
if (code) return code
const decoded = decodeHtmlEntities(unit.name) || unit.name || ''
return decoded.trim()
}
const getUnitDescription = (unit?: OrganizationalUnit | null) => {
if (!unit) return ''
const source = unit.description && unit.description.trim().length > 0 ? unit.description : unit.name
const decoded = decodeHtmlEntities(source) || source || ''
const trimmed = decoded.trim()
const label = getUnitDisplayLabel(unit)
if (trimmed && trimmed !== label) {
return trimmed
}
return ''
}
const handleUnitClick = (unit: OrganizationalUnit) => {
setSelectedUnit(unit)
loadUnitDetails(unit.id)
@ -147,7 +168,8 @@ export default function OrganizationChart({ onClose }: OrganizationChartProps) {
const renderUnit = (unit: any, level: number = 0) => {
const isMyUnit = myUnits.some(u => u.id === unit.id)
const isSearchMatch = searchTerm && unit.name.toLowerCase().includes(searchTerm.toLowerCase())
const searchable = `${getUnitDisplayLabel(unit)} ${getUnitDescription(unit)}`.toLowerCase()
const isSearchMatch = searchTerm && searchable.includes(searchTerm.toLowerCase())
return (
<div key={unit.id} className="flex flex-col items-center">
@ -167,7 +189,12 @@ export default function OrganizationChart({ onClose }: OrganizationChartProps) {
</div>
</div>
<div className="p-3">
<h4 className="font-semibold text-sm dark:text-white">{unit.name}</h4>
<h4 className="font-semibold text-sm dark:text-white">{getUnitDisplayLabel(unit)}</h4>
{getUnitDescription(unit) && (
<p className="text-xs text-gray-600 dark:text-gray-400 mt-1">
{getUnitDescription(unit)}
</p>
)}
{unit.hasFuehrungsstelle && (
<span className="inline-block px-2 py-1 mt-1 text-xs bg-yellow-100 dark:bg-yellow-900 text-yellow-800 dark:text-yellow-200 rounded">
FüSt
@ -313,8 +340,13 @@ export default function OrganizationChart({ onClose }: OrganizationChartProps) {
{selectedUnit && (
<div className="w-80 bg-gray-50 dark:bg-gray-800 border-l border-gray-200 dark:border-gray-700 p-4 overflow-y-auto">
<div className={`p-3 text-white rounded-lg mb-4 ${getUnitColor(selectedUnit.level || 0)}`}>
<h3 className="text-lg font-semibold">{selectedUnit.name}</h3>
{selectedUnit.code && <p className="text-sm opacity-90">{selectedUnit.code}</p>}
<h3 className="text-lg font-semibold">{getUnitDisplayLabel(selectedUnit)}</h3>
{getUnitDescription(selectedUnit) && (
<div className="mt-3 bg-white/10 rounded px-2 py-1">
<p className="text-xs font-semibold uppercase tracking-wide text-white/80">Aufgaben</p>
<p className="text-sm leading-snug text-white">{getUnitDescription(selectedUnit)}</p>
</div>
)}
</div>
{/* Tabs */}
@ -365,13 +397,6 @@ export default function OrganizationChart({ onClose }: OrganizationChartProps) {
)}
</div>
{selectedUnit.description && (
<div className="mt-4 p-3 bg-blue-50 dark:bg-blue-900/20 rounded">
<h4 className="font-semibold mb-1 dark:text-white">Beschreibung</h4>
<p className="text-sm dark:text-gray-300">{selectedUnit.description}</p>
</div>
)}
{user?.employeeId && (
<div className="mt-4">
<button

Datei anzeigen

@ -4,13 +4,24 @@ import type { OrganizationalUnit } from '@skillmate/shared'
import api from '../services/api'
import { ChevronRight, Building2, Search, X } from 'lucide-react'
interface OrganizationSelectorProps {
value?: string
onChange: (unitId: string | null, unitName: string) => void
disabled?: boolean
interface SelectedUnitDetails {
unit: OrganizationalUnit
storageValue: string
codePath: string
displayPath: string
namesPath: string
descriptionPath?: string
tasks?: string
}
export default function OrganizationSelector({ value, onChange, disabled }: OrganizationSelectorProps) {
interface OrganizationSelectorProps {
value?: string
onChange: (unitId: string | null, formattedValue: string, details?: SelectedUnitDetails) => void
disabled?: boolean
title?: string
}
export default function OrganizationSelector({ value, onChange, disabled, title }: OrganizationSelectorProps) {
const [showModal, setShowModal] = useState(false)
const [hierarchy, setHierarchy] = useState<OrganizationalUnit[]>([])
const [selectedUnit, setSelectedUnit] = useState<OrganizationalUnit | null>(null)
@ -26,14 +37,18 @@ export default function OrganizationSelector({ value, onChange, disabled }: Orga
}, [showModal])
useEffect(() => {
// Load current unit name if value exists
if (value && hierarchy.length > 0) {
const unit = findUnitById(hierarchy, value)
if (unit) {
setCurrentUnitName(getUnitPath(hierarchy, unit))
const selection = buildSelectionDetails(hierarchy, unit)
setCurrentUnitName(selection.displayPath)
setSelectedUnit(unit)
}
}
if (!value) {
setSelectedUnit(null)
setCurrentUnitName('')
}
}, [value, hierarchy])
const loadOrganization = async () => {
@ -73,25 +88,63 @@ export default function OrganizationSelector({ value, onChange, disabled }: Orga
return null
}
const getUnitPath = (units: OrganizationalUnit[], target: OrganizationalUnit): string => {
const path: string[] = []
const findPath = (units: OrganizationalUnit[], current: string[] = []): boolean => {
for (const unit of units) {
const newPath = [...current, unit.name]
if (unit.id === target.id) {
path.push(...newPath)
const buildSelectionDetails = (units: OrganizationalUnit[], target: OrganizationalUnit): SelectedUnitDetails => {
const pathUnits: OrganizationalUnit[] = []
const findPath = (nodes: OrganizationalUnit[], current: OrganizationalUnit[] = []): boolean => {
for (const node of nodes) {
const extended = [...current, node]
if (node.id === target.id) {
pathUnits.splice(0, pathUnits.length, ...extended)
return true
}
if (unit.children && findPath(unit.children, newPath)) {
if (node.children && findPath(node.children, extended)) {
return true
}
}
return false
}
findPath(units)
return path.join(' → ')
const normalize = (value?: string | null) => (value ?? '').trim()
const codeSegments = pathUnits
.map(unit => normalize(unit.code) || normalize(unit.name))
.filter(Boolean)
const nameSegments = pathUnits
.map(unit => normalize(unit.name))
.filter(Boolean)
const displaySegments = pathUnits
.map(unit => {
const code = normalize(unit.code)
const name = normalize(unit.name)
if (code && name && code !== name) {
return `${code}${name}`
}
return code || name || ''
})
.filter(Boolean)
const codePath = codeSegments.join(' -> ')
const displayPath = displaySegments.join(' → ')
const namesPath = nameSegments.join(' → ')
const descriptionPath = nameSegments.slice(0, -1).join(' → ') || undefined
const rawTask = normalize(target.description) || normalize(target.name)
const tasks = rawTask || undefined
const storageValue = tasks ? (codePath ? `${codePath} -> ${tasks}` : tasks) : codePath
return {
unit: target,
storageValue,
codePath: codePath || namesPath,
displayPath: displayPath || namesPath || tasks || '',
namesPath,
descriptionPath,
tasks
}
}
const toggleExpand = (unitId: string) => {
@ -107,10 +160,10 @@ export default function OrganizationSelector({ value, onChange, disabled }: Orga
}
const handleSelect = (unit: OrganizationalUnit) => {
const selection = buildSelectionDetails(hierarchy, unit)
setSelectedUnit(unit)
const path = getUnitPath(hierarchy, unit)
setCurrentUnitName(path)
onChange(unit.id, path)
setCurrentUnitName(selection.displayPath)
onChange(unit.id, selection.storageValue, selection)
setShowModal(false)
}
@ -193,9 +246,10 @@ export default function OrganizationSelector({ value, onChange, disabled }: Orga
type="text"
className="input-field w-full pr-10"
value={currentUnitName}
placeholder="Klicken zum Auswählen..."
placeholder="Organisationseinheit aus dem Organigramm wählen"
readOnly
disabled={disabled}
title={title}
onClick={() => !disabled && setShowModal(true)}
/>
<button

Datei anzeigen

@ -16,6 +16,12 @@ function segmentColor(i: number) {
return 'bg-purple-500 hover:bg-purple-600 dark:bg-purple-700 dark:hover:bg-purple-600'
}
function levelLabel(i: number): string {
if (i <= 3) return 'Anfänger'
if (i <= 7) return 'Fortgeschritten'
return 'Experte'
}
export default function SkillLevelBar({ value, onChange, min = 1, max = 10, disabled = false, showHelp = true }: SkillLevelBarProps) {
const handleKey = useCallback((e: React.KeyboardEvent<HTMLDivElement>) => {
if (disabled) return
@ -36,6 +42,8 @@ export default function SkillLevelBar({ value, onChange, min = 1, max = 10, disa
const current = typeof value === 'number' ? value : 0
const helpTooltip = showHelp ? 'Stufe 1: Anfänger · Stufe 5: Fortgeschritten · Stufe 10: Experte' : undefined
return (
<div className="space-y-2">
<div
@ -46,6 +54,7 @@ export default function SkillLevelBar({ value, onChange, min = 1, max = 10, disa
aria-valuenow={current || undefined}
tabIndex={disabled ? -1 : 0}
onKeyDown={handleKey}
title={helpTooltip}
>
{Array.from({ length: max }, (_, idx) => idx + 1).map(i => {
const active = i <= current
@ -58,20 +67,14 @@ export default function SkillLevelBar({ value, onChange, min = 1, max = 10, disa
? segmentColor(i)
: 'bg-border-default hover:bg-bg-gray dark:bg-dark-border/40 dark:hover:bg-dark-border/60'
} ${disabled ? 'cursor-not-allowed' : 'cursor-pointer'}`}
aria-label={`Level ${i}`}
aria-label={`Stufe ${i}`}
title={showHelp ? `Stufe ${i}${levelLabel(i)}` : undefined}
onClick={() => !disabled && onChange(i)}
/>
)
})}
<span className="ml-3 text-small text-secondary min-w-[2ch] text-right">{current || ''}</span>
</div>
{showHelp && (
<div className="text-small text-tertiary">
<span className="mr-4"><strong>1</strong> Anfänger</span>
<span className="mr-4"><strong>5</strong> Fortgeschritten</span>
<span><strong>10</strong> Experte</span>
</div>
)}
</div>
)
}

Datei anzeigen

@ -39,6 +39,16 @@ export function usePermissions() {
const hasPermission = (permission: string): boolean => {
if (!isAuthenticated || !user) return false
if (permission === 'employees:create') {
if (user.role === 'admin') return true
return user.role === 'superuser' && Boolean(user.canManageEmployees)
}
if (permission === 'employees:update') {
if (user.role === 'admin') return true
return user.role === 'superuser' && Boolean(user.canManageEmployees)
}
const rolePermissions = ROLE_PERMISSIONS[user.role] || []
return rolePermissions.includes(permission)
}
@ -51,7 +61,8 @@ export function usePermissions() {
}
const canCreateEmployee = (): boolean => {
return hasPermission('employees:create')
if (!isAuthenticated || !user) return false
return user.role === 'superuser' && Boolean(user.canManageEmployees)
}
const canEditEmployee = (employeeId?: string): boolean => {
@ -60,8 +71,8 @@ export function usePermissions() {
// Admins can edit anyone
if (user.role === 'admin') return true
// Superusers can edit anyone
if (user.role === 'superuser') return true
// Superusers can only edit when they are allowed to manage employees
if (user.role === 'superuser' && user.canManageEmployees) return true
// Users can only edit their own profile (if linked)
if (user.role === 'user' && employeeId && user.employeeId === employeeId) {

Datei anzeigen

@ -24,6 +24,10 @@ export const authApi = {
const response = await api.post('/auth/login', { email, password })
return response.data.data
},
forgotPassword: async (email: string) => {
const response = await api.post('/auth/forgot-password', { email })
return response.data
},
logout: async () => {
localStorage.removeItem('token')
}
@ -63,5 +67,31 @@ export const skillsApi = {
}
}
export const officialTitlesApi = {
getAll: async (): Promise<string[]> => {
const response = await api.get('/official-titles')
const list = Array.isArray(response.data?.data) ? response.data.data : []
return list.map((item: any) => item.label).filter((label: any) => typeof label === 'string')
}
}
export const positionCatalogApi = {
getAll: async (unitId?: string | null): Promise<string[]> => {
const params = unitId ? { unitId } : undefined
const response = await api.get('/positions', { params })
const list = Array.isArray(response.data?.data) ? response.data.data : []
const seen = new Set<string>()
return list
.map((item: any) => item?.label)
.filter((label: any) => typeof label === 'string' && label.trim().length > 0)
.filter((label: string) => {
const key = label.trim().toLowerCase()
if (seen.has(key)) return false
seen.add(key)
return true
})
}
}
export { api }
export default api

81
frontend/src/utils/text.ts Normale Datei
Datei anzeigen

@ -0,0 +1,81 @@
const namedEntities: Record<string, string> = {
amp: '&',
lt: '<',
gt: '>',
quot: '"',
apos: "'",
nbsp: '\u00A0',
slash: '/',
sol: '/',
frasl: '/',
}
const decodeOnce = (input: string): string => {
return input.replace(/&(#x?[0-9a-fA-F]+|#\d+|[a-zA-Z]+);/g, (match, entity) => {
if (!entity) return match
if (entity.startsWith('#')) {
const isHex = entity[1]?.toLowerCase() === 'x'
const num = isHex ? parseInt(entity.slice(2), 16) : parseInt(entity.slice(1), 10)
if (!Number.isNaN(num)) {
try {
return String.fromCodePoint(num)
} catch (err) {
return match
}
}
return match
}
const lowered = entity.toLowerCase()
if (namedEntities[lowered]) {
return namedEntities[lowered]
}
return match
})
}
export const decodeHtmlEntities = (value?: string | null): string | undefined => {
if (value === undefined || value === null) return undefined
let result = value
for (let i = 0; i < 3; i += 1) {
const decoded = decodeOnce(result)
if (decoded === result) break
result = decoded
}
return result
}
export const normalizeDepartment = (value?: string | null): string => {
if (!value) return ''
return (decodeHtmlEntities(value) || value || '').trim()
}
const splitPathAndTask = (value?: string | null): { path: string; task?: string } => {
const normalized = normalizeDepartment(value)
if (!normalized) return { path: '' }
const separator = ' -> '
const lastIndex = normalized.lastIndexOf(separator)
if (lastIndex === -1) {
return { path: normalized }
}
const path = normalized.slice(0, lastIndex)
const task = normalized.slice(lastIndex + separator.length)
return {
path: path || normalized,
task: task || undefined
}
}
export const formatDepartmentWithDescription = (
code?: string | null,
description?: string | null
): { label: string; description?: string; tasks?: string } => {
const { path, task } = splitPathAndTask(code)
const fallbackPath = normalizeDepartment(description)
const label = path || fallbackPath
const desc = fallbackPath && fallbackPath !== label ? fallbackPath : undefined
return {
label,
description: desc,
tasks: task || (desc && desc !== label ? desc : undefined)
}
}

Datei anzeigen

@ -7,6 +7,7 @@ import OfficeMapModal from '../components/OfficeMapModal'
import { employeeApi } from '../services/api'
import { useAuthStore } from '../stores/authStore'
import { isBooleanSkill } from '../utils/skillRules'
import { formatDepartmentWithDescription, normalizeDepartment } from '../utils/text'
export default function EmployeeDetail() {
const { id } = useParams()
@ -90,6 +91,11 @@ export default function EmployeeDetail() {
)
}
const departmentInfo = formatDepartmentWithDescription(employee.department, employee.departmentDescription)
const departmentDescriptionText = normalizeDepartment(departmentInfo.description)
const departmentTasks = normalizeDepartment(employee.departmentTasks || departmentInfo.description)
const showDepartmentDescription = departmentDescriptionText.length > 0 && departmentDescriptionText !== departmentTasks
// Hinweis: Verfügbarkeits-Badge wird im Mitarbeitenden-Detail nicht angezeigt
return (
@ -177,8 +183,17 @@ export default function EmployeeDetail() {
)}
<div>
<span className="text-tertiary">Dienststelle:</span>
<p className="text-secondary font-medium">{employee.department}</p>
<p className="text-secondary font-medium">{departmentInfo.label}</p>
{showDepartmentDescription && (
<p className="text-small text-tertiary mt-1">{departmentDescriptionText}</p>
)}
</div>
{departmentTasks && (
<div>
<span className="text-tertiary">Aufgaben der Dienststelle:</span>
<p className="text-secondary mt-1">{departmentTasks}</p>
</div>
)}
{employee.clearance && (
<div>
<span className="text-tertiary">Sicherheitsüberprüfung:</span>

Datei anzeigen

@ -1,14 +1,25 @@
import { useState } from 'react'
import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import type { Employee } from '@skillmate/shared'
import { employeeApi } from '../services/api'
import { SKILL_HIERARCHY, LANGUAGE_LEVELS } from '../data/skillCategories'
import { SKILL_HIERARCHY, LANGUAGE_LEVELS } from '@skillmate/shared'
import { employeeApi, officialTitlesApi, positionCatalogApi } from '../services/api'
import PhotoPreview from '../components/PhotoPreview'
import OrganizationSelector from '../components/OrganizationSelector'
import { isBooleanSkill } from '../utils/skillRules'
import { useAuthStore } from '../stores/authStore'
const DEFAULT_POSITION_OPTIONS = [
'Sachbearbeitung',
'stellvertretende Sachgebietsleitung',
'Sachgebietsleitung',
'Dezernatsleitung',
'Abteilungsleitung',
'Behördenleitung'
]
export default function EmployeeForm() {
const navigate = useNavigate()
const { user } = useAuthStore()
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [validationErrors, setValidationErrors] = useState<Record<string, string>>({})
@ -20,6 +31,8 @@ export default function EmployeeForm() {
position: '',
officialTitle: '',
department: '',
departmentDescription: '',
departmentTasks: '',
email: '',
phone: '',
mobile: '',
@ -31,20 +44,79 @@ export default function EmployeeForm() {
languages: [] as string[],
specializations: [] as string[]
})
const [primaryUnitId, setPrimaryUnitId] = useState<string | null>(null)
const [primaryUnitName, setPrimaryUnitName] = useState<string>('')
const [primaryUnitId, setPrimaryUnitId] = useState<string | null>(user?.powerUnitId || null)
const [primaryUnitName, setPrimaryUnitName] = useState<string>(user?.powerUnitName || '')
const [employeePhoto, setEmployeePhoto] = useState<string | null>(null)
const [photoFile, setPhotoFile] = useState<File | null>(null)
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
const [expandedSubCategories, setExpandedSubCategories] = useState<Set<string>>(new Set())
const [skillSearchTerm, setSkillSearchTerm] = useState('')
const [searchResults, setSearchResults] = useState<any[]>([])
const [officialTitleOptions, setOfficialTitleOptions] = useState<string[]>([])
const [positionOptions, setPositionOptions] = useState<string[]>(DEFAULT_POSITION_OPTIONS)
useEffect(() => {
if (!user || user.role !== 'superuser' || !user.canManageEmployees) {
navigate('/employees')
}
}, [user, navigate])
useEffect(() => {
setPrimaryUnitId(user?.powerUnitId || null)
setPrimaryUnitName(user?.powerUnitName || '')
}, [user])
useEffect(() => {
if (!primaryUnitName) return
setFormData(prev => {
if (prev.department) return prev
return { ...prev, department: primaryUnitName }
})
}, [primaryUnitName])
useEffect(() => {
const loadOfficialTitles = async () => {
try {
const titles = await officialTitlesApi.getAll()
setOfficialTitleOptions(titles)
} catch (error) {
console.error('Failed to load official titles', error)
setOfficialTitleOptions([])
}
}
loadOfficialTitles()
}, [])
useEffect(() => {
let isActive = true
const loadPositions = async () => {
try {
const options = await positionCatalogApi.getAll(primaryUnitId)
if (!isActive) return
setPositionOptions(options.length ? options : DEFAULT_POSITION_OPTIONS)
} catch (error) {
console.error('Failed to load position options', error)
if (!isActive) return
setPositionOptions(DEFAULT_POSITION_OPTIONS)
}
}
loadPositions()
return () => {
isActive = false
}
}, [primaryUnitId])
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
const { name, value } = e.target
setFormData(prev => ({ ...prev, [name]: value }))
setValidationErrors(prev => {
if (!prev[name]) return prev
const next = { ...prev }
delete next[name]
return next
})
}
const toggleCategory = (categoryId: string) => {
@ -175,17 +247,13 @@ export default function EmployeeForm() {
const validateForm = () => {
const errors: Record<string, string> = {}
if (!formData.firstName.trim()) errors.firstName = 'Vorname ist erforderlich'
if (!formData.lastName.trim()) errors.lastName = 'Nachname ist erforderlich'
if (!formData.employeeNumber.trim()) errors.employeeNumber = 'Personalnummer ist erforderlich'
if (!formData.position.trim()) errors.position = 'Position ist erforderlich'
if (!formData.department.trim()) errors.department = 'Abteilung ist erforderlich'
if (!formData.email.trim()) errors.email = 'E-Mail ist erforderlich'
else if (!/\S+@\S+\.\S+/.test(formData.email)) errors.email = 'Ungültige E-Mail-Adresse'
if (!formData.phone.trim()) errors.phone = 'Telefonnummer ist erforderlich'
if (!primaryUnitId) errors.primaryUnitId = 'Organisatorische Einheit ist erforderlich'
setValidationErrors(errors)
return Object.keys(errors).length === 0
}
@ -196,15 +264,30 @@ export default function EmployeeForm() {
setValidationErrors({})
if (!validateForm()) {
setError('Bitte füllen Sie alle Pflichtfelder aus')
setError('Bitte geben Sie Vorname, Nachname, E-Mail und eine Organisationseinheit an.')
return
}
setLoading(true)
try {
const trimmedFirstName = formData.firstName.trim()
const trimmedLastName = formData.lastName.trim()
const trimmedEmail = formData.email.trim()
const departmentValue = (formData.department || primaryUnitName || '').trim()
const positionValue = formData.position.trim()
const newEmployee: Partial<Employee> = {
...formData,
firstName: trimmedFirstName,
lastName: trimmedLastName,
email: trimmedEmail,
position: positionValue || 'Teammitglied',
department: departmentValue || 'Noch nicht zugewiesen',
employeeNumber: formData.employeeNumber.trim() || undefined,
phone: formData.phone.trim() || undefined,
mobile: formData.mobile.trim() || undefined,
office: formData.office.trim() || undefined,
skills: formData.skills.map((skill, index) => ({
id: skill.skillId || `skill-${index}`,
name: skill.name,
@ -225,16 +308,30 @@ export default function EmployeeForm() {
officialTitle: formData.officialTitle || undefined,
createdAt: new Date(),
updatedAt: new Date(),
createdBy: 'admin'
createdBy: user?.id ?? 'frontend'
}
const result = await employeeApi.create({ ...newEmployee, primaryUnitId })
const newEmployeeId = result.data.id
// Upload photo if we have one
const payload = {
...newEmployee,
department: newEmployee.department,
employeeNumber: newEmployee.employeeNumber,
phone: newEmployee.phone,
mobile: newEmployee.mobile,
office: newEmployee.office,
createUser: true,
userRole: 'user',
organizationUnitId: primaryUnitId,
organizationRole: 'mitarbeiter',
primaryUnitId
}
const result = await employeeApi.create(payload)
const newEmployeeId = result.data?.id
const temporaryPassword = result.data?.temporaryPassword as string | undefined
if (photoFile && newEmployeeId) {
const formData = new FormData()
formData.append('photo', photoFile)
const uploadForm = new FormData()
uploadForm.append('photo', photoFile)
try {
await fetch(`http://localhost:3001/api/upload/employee-photo/${newEmployeeId}`, {
@ -242,13 +339,17 @@ export default function EmployeeForm() {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: formData
body: uploadForm
})
} catch (uploadError) {
console.error('Failed to upload photo:', uploadError)
}
}
if (temporaryPassword) {
window.alert(`Benutzerkonto erstellt. Temporäres Passwort: ${temporaryPassword}\nBitte teilen Sie das Passwort sicher oder versenden Sie eine E-Mail über die Admin-Verwaltung.`)
}
navigate('/employees')
} catch (err: any) {
if (err.response?.status === 401) {
@ -349,7 +450,7 @@ export default function EmployeeForm() {
<div>
<label className="block text-sm font-medium text-secondary mb-2">
Personalnummer *
Personalnummer (optional)
</label>
<input
type="text"
@ -357,7 +458,7 @@ export default function EmployeeForm() {
value={formData.employeeNumber}
onChange={handleChange}
className={`input-field ${validationErrors.employeeNumber ? 'border-red-500 ring-red-200' : ''}`}
required
placeholder="Kann später ergänzt werden"
/>
{validationErrors.employeeNumber && (
<p className="mt-1 text-sm text-red-600">{validationErrors.employeeNumber}</p>
@ -383,16 +484,22 @@ export default function EmployeeForm() {
<div>
<label className="block text-sm font-medium text-secondary mb-2">
Position *
Position (optional)
</label>
<input
type="text"
<select
name="position"
value={formData.position}
onChange={handleChange}
className={`input-field ${validationErrors.position ? 'border-red-500 ring-red-200' : ''}`}
required
/>
>
<option value="" disabled>Neutrale Funktionsbezeichnung auswählen</option>
{positionOptions.map(option => (
<option key={option} value={option}>{option}</option>
))}
{formData.position && !positionOptions.includes(formData.position) && (
<option value={formData.position}>{`${formData.position} (bestehender Wert)`}</option>
)}
</select>
{validationErrors.position && (
<p className="mt-1 text-sm text-red-600">{validationErrors.position}</p>
)}
@ -402,19 +509,25 @@ export default function EmployeeForm() {
<label className="block text-sm font-medium text-secondary mb-2">
Amtsbezeichnung
</label>
<input
type="text"
<select
name="officialTitle"
value={formData.officialTitle}
onChange={handleChange}
className="input-field"
placeholder="z. B. KOK, KHK, EKHK"
/>
>
<option value="">Bitte auswählen</option>
{officialTitleOptions.map(option => (
<option key={option} value={option}>{option}</option>
))}
{formData.officialTitle && !officialTitleOptions.includes(formData.officialTitle) && (
<option value={formData.officialTitle}>{`${formData.officialTitle} (bestehender Wert)`}</option>
)}
</select>
</div>
<div>
<label className="block text-sm font-medium text-secondary mb-2">
Abteilung *
Abteilung (optional wird aus der Organisationseinheit vorgeschlagen)
</label>
<input
type="text"
@ -422,7 +535,7 @@ export default function EmployeeForm() {
value={formData.department}
onChange={handleChange}
className={`input-field ${validationErrors.department ? 'border-red-500 ring-red-200' : ''}`}
required
placeholder="Wird automatisch nach Auswahl der Einheit befüllt"
/>
{validationErrors.department && (
<p className="mt-1 text-sm text-red-600">{validationErrors.department}</p>
@ -435,10 +548,18 @@ export default function EmployeeForm() {
</label>
<OrganizationSelector
value={primaryUnitId || undefined}
onChange={(unitId, unitName) => {
onChange={(unitId, formattedValue, details) => {
if (user?.canManageEmployees && user?.powerUnitId) return
setPrimaryUnitId(unitId)
setPrimaryUnitName(unitName)
setPrimaryUnitName(details?.displayPath || formattedValue)
setFormData(prev => ({
...prev,
department: formattedValue || '',
departmentDescription: details?.descriptionPath || details?.namesPath || '',
departmentTasks: details?.tasks || ''
}))
}}
disabled={Boolean(user?.canManageEmployees && user?.powerUnitId)}
/>
<p className="text-tertiary text-sm mt-2">{primaryUnitName || 'Bitte auswählen'}</p>
{validationErrors.primaryUnitId && (
@ -448,7 +569,7 @@ export default function EmployeeForm() {
<div>
<label className="block text-sm font-medium text-secondary mb-2">
Telefon *
Telefon (optional)
</label>
<input
type="tel"
@ -456,7 +577,7 @@ export default function EmployeeForm() {
value={formData.phone}
onChange={handleChange}
className={`input-field ${validationErrors.phone ? 'border-red-500 ring-red-200' : ''}`}
required
placeholder="Kann später ergänzt werden"
/>
{validationErrors.phone && (
<p className="mt-1 text-sm text-red-600">{validationErrors.phone}</p>

Datei anzeigen

@ -3,13 +3,12 @@ import { useNavigate } from 'react-router-dom'
import { SearchIcon } from '../components/icons'
import EmployeeCard from '../components/EmployeeCard'
import { employeeApi } from '../services/api'
import { useAuthStore } from '../stores/authStore'
import type { Employee } from '@skillmate/shared'
import { usePermissions } from '../hooks/usePermissions'
import { normalizeDepartment } from '../utils/text'
export default function EmployeeList() {
const navigate = useNavigate()
const { user } = useAuthStore()
const { canCreateEmployee } = usePermissions()
const [employees, setEmployees] = useState<Employee[]>([])
const [searchTerm, setSearchTerm] = useState('')
@ -59,30 +58,48 @@ export default function EmployeeList() {
}
useEffect(() => {
const skillFilter = filters.skills.trim().toLowerCase()
const searchFilter = searchTerm.trim().toLowerCase()
let filtered = employees.filter(emp => {
// Text search
const matchesSearch = searchTerm === '' ||
`${emp.firstName} ${emp.lastName}`.toLowerCase().includes(searchTerm.toLowerCase()) ||
emp.department.toLowerCase().includes(searchTerm.toLowerCase()) ||
emp.position.toLowerCase().includes(searchTerm.toLowerCase()) ||
emp.specializations.some(spec => spec.toLowerCase().includes(searchTerm.toLowerCase()))
// Department filter
const matchesDepartment = filters.department === '' || emp.department === filters.department
// Availability filter
const matchesAvailability = filters.availability === '' || emp.availability === filters.availability
// Skills filter (basic - später erweitern)
const matchesSkills = filters.skills === '' ||
emp.specializations.some(spec => spec.toLowerCase().includes(filters.skills.toLowerCase()))
const departmentLabel = normalizeDepartment(emp.department)
const departmentDescription = normalizeDepartment(emp.departmentDescription)
const departmentTasks = normalizeDepartment(emp.departmentTasks || emp.departmentDescription)
const matchesSkillSearch = (emp.skills || []).some(skill =>
(skill.name || '').toLowerCase().includes(searchFilter) ||
(skill.category || '').toLowerCase().includes(searchFilter)
)
const matchesSpecializationSearch = emp.specializations.some(spec => spec.toLowerCase().includes(searchFilter))
const matchesSearch = searchFilter === '' ||
`${emp.firstName} ${emp.lastName}`.toLowerCase().includes(searchFilter) ||
departmentLabel.toLowerCase().includes(searchFilter) ||
departmentDescription.toLowerCase().includes(searchFilter) ||
departmentTasks.toLowerCase().includes(searchFilter) ||
emp.position.toLowerCase().includes(searchFilter) ||
matchesSkillSearch ||
matchesSpecializationSearch
const matchesDepartment = !filters.department || departmentLabel === filters.department
const matchesAvailability = !filters.availability || emp.availability === filters.availability
const matchesSkills = skillFilter === '' ||
(emp.skills || []).some(skill =>
(skill.name || '').toLowerCase().includes(skillFilter) ||
(skill.category || '').toLowerCase().includes(skillFilter)
) ||
emp.specializations.some(spec => spec.toLowerCase().includes(skillFilter))
return matchesSearch && matchesDepartment && matchesAvailability && matchesSkills
})
setFilteredEmployees(filtered)
}, [searchTerm, employees, filters])
const departmentOptions = Array.from(new Set(
employees.map(emp => normalizeDepartment(emp.department)).filter(Boolean)
)).sort()
return (
<div>
<div className="flex justify-between items-center mb-8">
@ -136,11 +153,9 @@ export default function EmployeeList() {
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
>
<option value="">Alle Dienststellen</option>
<option value="Cybercrime">Cybercrime</option>
<option value="Staatsschutz">Staatsschutz</option>
<option value="Kriminalpolizei">Kriminalpolizei</option>
<option value="IT">IT</option>
<option value="Verwaltung">Verwaltung</option>
{departmentOptions.map(option => (
<option key={option} value={option}>{option}</option>
))}
</select>
</div>
@ -183,6 +198,7 @@ export default function EmployeeList() {
key={employee.id}
employee={employee}
onClick={() => navigate(`/employees/${employee.id}`)}
onDeputyNavigate={(id) => navigate(`/employees/${id}`)}
/>
))}
</div>

Datei anzeigen

@ -10,6 +10,10 @@ export default function Login() {
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [forgotOpen, setForgotOpen] = useState(false)
const [forgotEmail, setForgotEmail] = useState('')
const [forgotMessage, setForgotMessage] = useState('')
const [forgotLoading, setForgotLoading] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
@ -28,6 +32,43 @@ export default function Login() {
}
}
const toggleForgotPassword = () => {
setForgotOpen((prev) => {
const next = !prev
if (!prev) {
setForgotEmail((current) => current || email)
setForgotMessage('')
}
if (prev) {
setForgotEmail('')
setForgotMessage('')
}
return next
})
}
const handleForgotPassword = async (e: React.FormEvent) => {
e.preventDefault()
const fallbackMessage = 'Falls die E-Mail im System hinterlegt ist, senden wir zeitnah ein neues Passwort.'
if (!forgotEmail.trim()) {
setForgotMessage(fallbackMessage)
return
}
try {
setForgotLoading(true)
setForgotMessage('')
const response = await authApi.forgotPassword(forgotEmail.trim())
setForgotMessage(response?.message || fallbackMessage)
} catch (err) {
setForgotMessage(fallbackMessage)
} finally {
setForgotLoading(false)
}
}
return (
<div className="min-h-screen bg-primary flex items-center justify-center">
<div className="card max-w-md w-full">
@ -82,10 +123,53 @@ export default function Login() {
</button>
</form>
<div className="mt-4 text-center">
<button
type="button"
onClick={toggleForgotPassword}
className="text-sm text-primary hover:underline"
>
Passwort vergessen?
</button>
</div>
{forgotOpen && (
<form onSubmit={handleForgotPassword} className="mt-6 space-y-4">
<div>
<label htmlFor="forgot-email" className="block text-sm font-medium text-secondary mb-2">
E-Mail-Adresse für Passwort-Reset
</label>
<input
id="forgot-email"
type="email"
value={forgotEmail}
onChange={(e) => setForgotEmail(e.target.value)}
className="input-field"
placeholder="E-Mail-Adresse eingeben"
required
/>
</div>
{forgotMessage && (
<div className="bg-info-bg text-info p-3 rounded-input text-sm">
{forgotMessage}
</div>
)}
<button
type="submit"
disabled={forgotLoading}
className="btn-secondary w-full"
>
{forgotLoading ? 'Wird angefordert...' : 'Neues Passwort anfordern'}
</button>
</form>
)}
<div className="mt-6 text-center text-sm text-tertiary">
<p>Für erste Anmeldung wenden Sie sich an Ihren Administrator</p>
</div>
</div>
</div>
)
}
}

Datei anzeigen

@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useAuthStore } from '../stores/authStore'
import { employeeApi } from '../services/api'
import { employeeApi, officialTitlesApi, positionCatalogApi } from '../services/api'
import PhotoUpload from '../components/PhotoUpload'
import SkillLevelBar from '../components/SkillLevelBar'
import DeputyManagement from '../components/DeputyManagement'
@ -9,6 +9,26 @@ import { isBooleanSkill } from '../utils/skillRules'
interface SkillSelection { categoryId: string; subCategoryId: string; skillId: string; name: string; level: string }
const AVAILABILITY_OPTIONS = [
{ value: 'available', label: 'Verfügbar' },
{ value: 'busy', label: 'Beschäftigt' },
{ value: 'away', label: 'Abwesend' },
{ value: 'vacation', label: 'Urlaub' },
{ value: 'sick', label: 'Erkrankt' },
{ value: 'training', label: 'Fortbildung' },
{ value: 'operation', label: 'Im Einsatz' },
{ value: 'unavailable', label: 'Nicht verfügbar' }
]
const DEFAULT_POSITION_OPTIONS = [
'Sachbearbeitung',
'stellvertretende Sachgebietsleitung',
'Sachgebietsleitung',
'Dezernatsleitung',
'Abteilungsleitung',
'Behördenleitung'
]
export default function MyProfile() {
const { user } = useAuthStore()
const employeeId = user?.employeeId
@ -17,23 +37,17 @@ export default function MyProfile() {
const [error, setError] = useState('')
const [success, setSuccess] = useState('')
const [form, setForm] = useState<any | null>(null)
const [catalog, setCatalog] = useState<{ id: string; name: string; subcategories: { id: string; name: string; skills: { id: string; name: string }[] }[] }[]>([])
const [skills, setSkills] = useState<SkillSelection[]>([])
const [activeTab, setActiveTab] = useState<'profile' | 'deputies'>('profile')
const [currentUnitId, setCurrentUnitId] = useState<string | null>(null)
const [myUnits, setMyUnits] = useState<any[]>([])
const AVAILABILITY_OPTIONS = [
{ value: 'available', label: 'Verfügbar' },
{ value: 'busy', label: 'Beschäftigt' },
{ value: 'away', label: 'Abwesend' },
{ value: 'vacation', label: 'Urlaub' },
{ value: 'sick', label: 'Erkrankt' },
{ value: 'training', label: 'Fortbildung' },
{ value: 'operation', label: 'Im Einsatz' },
{ value: 'parttime', label: 'Teilzeit' },
{ value: 'unavailable', label: 'Nicht verfügbar' }
]
const [form, setForm] = useState<any | null>(null)
const [catalog, setCatalog] = useState<{ id: string; name: string; subcategories: { id: string; name: string; skills: { id: string; name: string }[] }[] }[]>([])
const [skills, setSkills] = useState<SkillSelection[]>([])
const [activeTab, setActiveTab] = useState<'profile' | 'deputies'>('profile')
const [currentUnitId, setCurrentUnitId] = useState<string | null>(null)
const [myUnits, setMyUnits] = useState<any[]>([])
const [officialTitleOptions, setOfficialTitleOptions] = useState<string[]>([])
const [positionOptions, setPositionOptions] = useState<string[]>(DEFAULT_POSITION_OPTIONS)
const [showAvailabilityHint, setShowAvailabilityHint] = useState(false)
const [highlightDelegations, setHighlightDelegations] = useState(false)
const highlightTimeoutRef = useRef<number | undefined>(undefined)
useEffect(() => {
if (!employeeId) {
@ -43,6 +57,46 @@ const AVAILABILITY_OPTIONS = [
load()
}, [employeeId])
useEffect(() => {
const loadOfficialTitles = async () => {
try {
const titles = await officialTitlesApi.getAll()
setOfficialTitleOptions(titles)
} catch (error) {
console.error('Failed to load official titles', error)
setOfficialTitleOptions([])
}
}
loadOfficialTitles()
}, [])
useEffect(() => {
let isActive = true
const loadPositions = async () => {
try {
const titles = await positionCatalogApi.getAll(currentUnitId)
if (!isActive) return
setPositionOptions(titles.length ? titles : DEFAULT_POSITION_OPTIONS)
} catch (error) {
console.error('Failed to load position options', error)
if (!isActive) return
setPositionOptions(DEFAULT_POSITION_OPTIONS)
}
}
loadPositions()
return () => {
isActive = false
}
}, [currentUnitId])
useEffect(() => {
return () => {
if (highlightTimeoutRef.current) {
window.clearTimeout(highlightTimeoutRef.current)
}
}
}, [])
const load = async () => {
if (!employeeId) return
setLoading(true)
@ -50,6 +104,7 @@ const AVAILABILITY_OPTIONS = [
try {
// Load employee first
const data = await employeeApi.getById(employeeId)
const availability = data.availability || 'available'
setForm({ ...data, email: user?.email || data.email || '' })
const mapped: SkillSelection[] = (data.skills || []).map((s: any) => {
const catStr = s.category || ''
@ -67,6 +122,7 @@ const AVAILABILITY_OPTIONS = [
}
})
setSkills(mapped)
setShowAvailabilityHint(availability !== 'available')
// Load my organizational units
try {
@ -118,17 +174,49 @@ const AVAILABILITY_OPTIONS = [
setSkills(prev => prev.map(s => (s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId) ? { ...s, level } : s))
}
const triggerDelegationHighlight = () => {
if (highlightTimeoutRef.current) {
window.clearTimeout(highlightTimeoutRef.current)
}
setHighlightDelegations(true)
highlightTimeoutRef.current = window.setTimeout(() => {
setHighlightDelegations(false)
highlightTimeoutRef.current = undefined
}, 5000)
}
const handleAvailabilityChange = (value: string) => {
setForm((prev: any) => ({ ...prev, availability: value }))
const shouldHighlight = value !== 'available'
setShowAvailabilityHint(shouldHighlight)
if (shouldHighlight) {
triggerDelegationHighlight()
} else {
if (highlightTimeoutRef.current) {
window.clearTimeout(highlightTimeoutRef.current)
highlightTimeoutRef.current = undefined
}
setHighlightDelegations(false)
}
}
const isSkillSelected = (categoryId: string, subCategoryId: string, skillId: string) =>
skills.some(s => s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId)
const getSkillLevel = (categoryId: string, subCategoryId: string, skillId: string) =>
(skills.find(s => s.categoryId === categoryId && s.subCategoryId === subCategoryId && s.skillId === skillId)?.level) || ''
const handleOrganizationChange = async (unitId: string | null, unitName: string) => {
const handleOrganizationChange = async (unitId: string | null, formattedValue: string, details?: { descriptionPath?: string; namesPath: string; tasks?: string } | null) => {
setCurrentUnitId(unitId)
setForm((prev: any) => ({
...prev,
department: formattedValue || '',
departmentDescription: details?.descriptionPath || details?.namesPath || '',
departmentTasks: details?.tasks || ''
}))
if (unitId && employeeId) {
try {
// Save organization assignment
await fetch(((import.meta as any).env?.VITE_API_URL || 'http://localhost:3004/api') + '/organization/assignments', {
method: 'POST',
headers: {
@ -136,14 +224,12 @@ const AVAILABILITY_OPTIONS = [
'Authorization': `Bearer ${localStorage.getItem('token')}`
},
body: JSON.stringify({
employeeId: employeeId,
unitId: unitId,
employeeId,
unitId,
role: 'mitarbeiter',
isPrimary: true
})
})
// Update department field with unit name for backward compatibility
setForm((prev: any) => ({ ...prev, department: unitName }))
} catch (error) {
console.error('Failed to assign unit:', error)
}
@ -228,13 +314,17 @@ const AVAILABILITY_OPTIONS = [
<div className="flex gap-4 mb-6 border-b border-gray-200 dark:border-gray-700">
<button
onClick={() => setActiveTab('profile')}
className={`pb-2 px-1 ${activeTab === 'profile' ? 'border-b-2 border-blue-600 text-blue-600' : 'text-gray-600 dark:text-gray-400'}`}
className={`pb-2 px-1 transition-colors ${activeTab === 'profile' ? 'border-b-2 border-blue-600 text-blue-600' : 'text-gray-600 dark:text-gray-400'}`}
>
Profildaten
</button>
<button
onClick={() => setActiveTab('deputies')}
className={`pb-2 px-1 ${activeTab === 'deputies' ? 'border-b-2 border-blue-600 text-blue-600' : 'text-gray-600 dark:text-gray-400'}`}
className={`pb-2 px-1 transition-colors rounded-sm ${
activeTab === 'deputies'
? 'border-b-2 border-blue-600 text-blue-600'
: 'text-gray-600 dark:text-gray-400'
} ${highlightDelegations ? 'ring-2 ring-amber-400 ring-offset-1 ring-offset-white dark:ring-offset-gray-900 bg-amber-50 dark:bg-amber-900/30 animate-pulse' : ''}`}
>
Vertretungen
</button>
@ -259,33 +349,45 @@ const AVAILABILITY_OPTIONS = [
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-body font-medium text-secondary mb-2">E-Mail</label>
<input className="input-field w-full disabled:opacity-70" value={user?.email || form.email || ''} disabled readOnly placeholder="wird aus Login übernommen" title="Wird automatisch aus dem Login gesetzt" />
<p className="text-small text-tertiary mt-1">Wird automatisch aus dem Login übernommen. Änderung ggf. im Admin Panel.</p>
<input className="input-field w-full disabled:opacity-70" value={user?.email || form.email || ''} disabled readOnly placeholder="Wird automatisch aus dem Login übernommen" title="Wird automatisch aus dem Login übernommen" />
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Position</label>
<input
<select
className="input-field w-full"
value={form.position || ''}
onChange={(e) => setForm((p: any) => ({ ...p, position: e.target.value }))}
placeholder="z. B. Sachbearbeitung, Teamleitung"
/>
<p className="text-small text-tertiary mt-1">Beispiele: Sachbearbeitung, Teamleitung, Stabsstelle.</p>
title="Neutrale Funktionsbezeichnung auswählen"
>
<option value="" disabled>Neutrale Funktionsbezeichnung auswählen</option>
{positionOptions.map(option => (
<option key={option} value={option}>{option}</option>
))}
{form.position && !positionOptions.includes(form.position) && (
<option value={form.position}>{`${form.position} (bestehender Wert)`}</option>
)}
</select>
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Amtsbezeichnung</label>
<input
<select
className="input-field w-full"
value={form.officialTitle || ''}
onChange={(e) => setForm((p: any) => ({ ...p, officialTitle: e.target.value }))}
placeholder="z. B. KOK, KHK, EKHK"
/>
<p className="text-small text-tertiary mt-1">Freifeld für Amts- bzw. Dienstbezeichnungen (z. B. KOK, RBe, EKHK).</p>
title="Dienstliche Amtsbezeichnung auswählen"
>
<option value="" disabled>Amtsbezeichnung auswählen</option>
{officialTitleOptions.map(option => (
<option key={option} value={option}>{option}</option>
))}
{form.officialTitle && !officialTitleOptions.includes(form.officialTitle) && (
<option value={form.officialTitle}>{`${form.officialTitle} (bestehender Wert)`}</option>
)}
</select>
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">NW-Kennung</label>
<input className="input-field w-full" value={form.employeeNumber || ''} onChange={(e) => setForm((p: any) => ({ ...p, employeeNumber: e.target.value }))} placeholder="z. B. NW068111" />
<p className="text-small text-tertiary mt-1">Ihre behördliche Kennung, z. B. NW068111.</p>
<input className="input-field w-full" value={form.employeeNumber || ''} onChange={(e) => setForm((p: any) => ({ ...p, employeeNumber: e.target.value }))} placeholder="z. B. NW068111" title="Behördliche Kennung, z. B. NW068111" />
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Dienststelle</label>
@ -293,41 +395,50 @@ const AVAILABILITY_OPTIONS = [
value={currentUnitId || undefined}
onChange={handleOrganizationChange}
disabled={false}
title="Organisationseinheit aus dem Organigramm auswählen"
/>
<p className="text-small text-tertiary mt-1">Wählen Sie Ihre Organisationseinheit aus dem Organigramm.</p>
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Telefon</label>
<input className="input-field w-full" value={form.phone || ''} onChange={(e) => setForm((p: any) => ({ ...p, phone: e.target.value }))} placeholder="z. B. +49 30 12345-100" />
<p className="text-small text-tertiary mt-1">Bitte Rufnummern im internationalen Format angeben (z. B. +49 ...).</p>
<input className="input-field w-full" value={form.phone || ''} onChange={(e) => setForm((p: any) => ({ ...p, phone: e.target.value }))} placeholder="z. B. +49 30 12345-100" title="Bitte Rufnummer im internationalen Format angeben" />
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Mobil</label>
<input className="input-field w-full" value={form.mobile || ''} onChange={(e) => setForm((p: any) => ({ ...p, mobile: e.target.value }))} placeholder="z. B. +49 171 1234567" />
<p className="text-small text-tertiary mt-1">Bitte Rufnummern im internationalen Format angeben (z. B. +49 ...).</p>
<input className="input-field w-full" value={form.mobile || ''} onChange={(e) => setForm((p: any) => ({ ...p, mobile: e.target.value }))} placeholder="z. B. +49 171 1234567" title="Bitte Rufnummer im internationalen Format angeben" />
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Büro</label>
<input className="input-field w-full" value={form.office || ''} onChange={(e) => setForm((p: any) => ({ ...p, office: e.target.value }))} placeholder="z. B. Gebäude A, 3.OG, Raum 3.12" />
<p className="text-small text-tertiary mt-1">Angabe zum Standort, z. B. Gebäude, Etage und Raum.</p>
<input className="input-field w-full" value={form.office || ''} onChange={(e) => setForm((p: any) => ({ ...p, office: e.target.value }))} placeholder="z. B. Gebäude A, 3.OG, Raum 3.12" title="Standort mit Gebäude, Etage und Raum angeben" />
</div>
<div>
<label className="block text-body font-medium text-secondary mb-2">Verfügbarkeit</label>
<select
className="input-field w-full"
value={form.availability || 'available'}
onChange={(e) => setForm((p: any) => ({ ...p, availability: e.target.value }))}
onChange={(e) => handleAvailabilityChange(e.target.value)}
title="Status wird in Mitarbeitendenübersicht und Teamplanung angezeigt"
>
{AVAILABILITY_OPTIONS.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
<p className="text-small text-tertiary mt-1">Dieser Status wird in der Mitarbeitendenübersicht und Teamplanung angezeigt.</p>
{showAvailabilityHint && (
<div className="mt-2 rounded-input border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-700 dark:border-amber-500 dark:bg-amber-900/30 dark:text-amber-200">
Hinweis: Bitte stimmen Sie eine Vertretung im Reiter Vertretungen ab, solange Sie nicht verfügbar sind.
</div>
)}
</div>
</div>
</div>
</div>
<div className="flex justify-end mt-4">
<button onClick={onSave} disabled={saving} className="btn-primary">
{saving ? 'Speichere...' : 'Änderungen speichern'}
</button>
</div>
<div className="card mt-6">
<h2 className="text-title-card font-poppins font-semibold text-primary mb-4">Kompetenzen</h2>
<div className="space-y-4">
@ -341,26 +452,33 @@ const AVAILABILITY_OPTIONS = [
{sub.skills.map(skill => {
const booleanSkill = isBooleanSkill(category.id, sub.id)
const selected = isSkillSelected(category.id, sub.id, skill.id)
const skillInputId = `skill-${category.id}-${sub.id}-${skill.id}`
return (
<div
key={`${category.id}-${sub.id}-${skill.id}`}
className={`p-2 border rounded-input ${selected ? 'border-primary-blue bg-bg-accent' : 'border-border-default'}`}
>
<label className="flex items-center justify-between">
<span className="text-body text-secondary">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<label
htmlFor={skillInputId}
className="flex items-start gap-2 flex-1 min-w-0 text-body text-secondary cursor-pointer"
>
<input
id={skillInputId}
type="checkbox"
className="mr-2"
className="mt-0.5 shrink-0"
checked={selected}
onChange={() => handleSkillToggle(category.id, sub.id, skill.id, skill.name)}
/>
{skill.name}
</span>
<span className="truncate" title={skill.name}>{skill.name}</span>
</label>
{selected && (
booleanSkill ? (
<span className="ml-3 text-small font-medium text-green-700 dark:text-green-400">Ja</span>
<span className="sm:ml-3 text-small font-medium text-green-700 dark:text-green-400">Ja</span>
) : (
<div className="ml-3 flex-1">
<div className="sm:ml-3 w-full sm:w-56 md:w-64">
<SkillLevelBar
value={Number(getSkillLevel(category.id, sub.id, skill.id)) || ''}
onChange={(val) => handleSkillLevelChange(category.id, sub.id, skill.id, String(val))}
@ -368,7 +486,7 @@ const AVAILABILITY_OPTIONS = [
</div>
)
)}
</label>
</div>
</div>
)
})}

Datei anzeigen

@ -4,6 +4,7 @@ import { SearchIcon } from '../components/icons'
import EmployeeCard from '../components/EmployeeCard'
import { useNavigate } from 'react-router-dom'
import { employeeApi } from '../services/api'
import { normalizeDepartment } from '../utils/text'
// Import the skill hierarchy - we'll load it dynamically in useEffect
type SkillWithStats = {
@ -194,8 +195,11 @@ export default function SkillSearch() {
const searchLower = freeSearchTerm.toLowerCase()
const results = allEmployees.filter(employee => {
// Search in name, department, position
const departmentLabel = normalizeDepartment(employee.department)
const departmentDescription = normalizeDepartment(employee.departmentDescription)
if (`${employee.firstName} ${employee.lastName}`.toLowerCase().includes(searchLower) ||
employee.department?.toLowerCase().includes(searchLower) ||
departmentLabel.toLowerCase().includes(searchLower) ||
departmentDescription.toLowerCase().includes(searchLower) ||
employee.position?.toLowerCase().includes(searchLower)) {
return true
}

Datei anzeigen

@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'
import type { Employee } from '@skillmate/shared'
import { employeeApi } from '../services/api'
import { SearchIcon } from '../components/icons'
import { normalizeDepartment, formatDepartmentWithDescription } from '../utils/text'
type TeamPosition = {
id: string
@ -146,7 +147,9 @@ export default function TeamZusammenstellung() {
}
// Get unique departments and positions
const departments = Array.from(new Set(employees.map(e => e.department).filter(Boolean)))
const departments = Array.from(new Set(
employees.map(e => normalizeDepartment(e.department)).filter(Boolean)
))
const positions = Array.from(new Set(employees.map(e => e.position).filter(Boolean)))
// Toggle category selection
@ -241,7 +244,7 @@ export default function TeamZusammenstellung() {
// Department filter
if (selectedDepartment) {
filtered = filtered.filter(emp => emp.department === selectedDepartment)
filtered = filtered.filter(emp => normalizeDepartment(emp.department) === selectedDepartment)
}
// Position filter
@ -652,7 +655,9 @@ export default function TeamZusammenstellung() {
filteredEmployees.map((employee: any) => {
const isAssigned = teamPositions.some(p => p.assignedEmployeeId === employee.id)
const matchScore = employee.matchScore || 0
const departmentInfo = formatDepartmentWithDescription(employee.department, employee.departmentDescription)
const departmentText = departmentInfo.description ? `${departmentInfo.label}${departmentInfo.description}` : departmentInfo.label
return (
<div
key={employee.id}
@ -690,7 +695,7 @@ export default function TeamZusammenstellung() {
<div className="text-sm text-tertiary">
{employee.position}
{employee.officialTitle ? `${employee.officialTitle}` : ''}
{`${employee.department}`}
{departmentText ? `${departmentText}` : ''}
</div>
</div>