feat: implement Phase 2 (Go Agent) and Phase 3 (React Frontend MVP)

Phase 2 - Go Agent Core:
- gRPC client with exponential backoff reconnect logic
- Command executor (PowerShell/sh cross-platform)
- Proto stubs regenerated with module= option (correct output path)
- gRPC upgraded to v1.79.3 (BidiStreamingClient support)

Phase 3 - React Frontend MVP:
- Vite + React 18 + TypeScript setup with Tailwind CSS v4
- TanStack Query for data fetching, API client + TypeScript types
- Dashboard page: stats cards (agents/status/tickets) + sortable agents table
- Agent detail page: CPU/RAM charts (Recharts), disk usage, shell command executor
- Tickets page: CRUD with modals, filters, sortable table
- Dark mode with CSS custom properties

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Claude Agent
2026-03-19 12:42:52 +01:00
parent 51052261f5
commit 418fc5b6d5
30 changed files with 7670 additions and 24 deletions

184
Frontend/src/App.css Normal file
View File

@@ -0,0 +1,184 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}

123
Frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,123 @@
import { useState } from 'react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { LayoutDashboard, Ticket, Menu, X } from 'lucide-react'
import { DashboardPage } from './pages/DashboardPage'
import { AgentDetailPage } from './pages/AgentDetailPage'
import TicketsPage from './pages/TicketsPage'
import { cn } from './lib/utils'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 30_000,
retry: 2,
},
},
})
type Page = 'dashboard' | 'agent-detail' | 'tickets'
interface NavItem {
id: Page
label: string
icon: React.ReactNode
}
const navItems: NavItem[] = [
{ id: 'dashboard', label: 'Dashboard', icon: <LayoutDashboard size={18} /> },
{ id: 'tickets', label: 'Tickets', icon: <Ticket size={18} /> },
]
function AppContent() {
const [page, setPage] = useState<Page>('dashboard')
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null)
const [sidebarOpen, setSidebarOpen] = useState(true)
function handleSelectAgent(agentId: string) {
setSelectedAgentId(agentId)
setPage('agent-detail')
}
function handleBack() {
setPage('dashboard')
setSelectedAgentId(null)
}
return (
<div className="min-h-screen bg-background text-foreground flex">
{/* Sidebar */}
<aside
className={cn(
'flex flex-col border-r border-border bg-card transition-all duration-200',
sidebarOpen ? 'w-56' : 'w-14',
)}
>
{/* Logo */}
<div className="flex items-center gap-3 px-4 py-4 border-b border-border">
<div className="w-7 h-7 rounded-md bg-primary flex items-center justify-center text-primary-foreground font-bold text-sm flex-shrink-0">
N
</div>
{sidebarOpen && (
<span className="font-semibold text-foreground truncate">NexusRMM</span>
)}
<button
onClick={() => setSidebarOpen(!sidebarOpen)}
className="ml-auto text-muted-foreground hover:text-foreground"
>
{sidebarOpen ? <X size={16} /> : <Menu size={16} />}
</button>
</div>
{/* Nav */}
<nav className="flex-1 py-3 px-2 flex flex-col gap-1">
{navItems.map((item) => (
<button
key={item.id}
onClick={() => {
setPage(item.id)
setSelectedAgentId(null)
}}
className={cn(
'flex items-center gap-3 px-2 py-2 rounded-md text-sm transition-colors w-full text-left',
page === item.id || (page === 'agent-detail' && item.id === 'dashboard')
? 'bg-primary/15 text-primary'
: 'text-muted-foreground hover:text-foreground hover:bg-accent',
)}
>
<span className="flex-shrink-0">{item.icon}</span>
{sidebarOpen && <span>{item.label}</span>}
</button>
))}
</nav>
{/* Version */}
{sidebarOpen && (
<div className="px-4 py-3 text-xs text-muted-foreground border-t border-border">
NexusRMM v0.1.0
</div>
)}
</aside>
{/* Main content */}
<main className="flex-1 overflow-auto">
{page === 'dashboard' && (
<DashboardPage onSelectAgent={handleSelectAgent} />
)}
{page === 'agent-detail' && selectedAgentId && (
<AgentDetailPage agentId={selectedAgentId} onBack={handleBack} />
)}
{page === 'tickets' && <TicketsPage />}
</main>
</div>
)
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<AppContent />
</QueryClientProvider>
)
}
export default App

View File

@@ -0,0 +1,50 @@
import type {
Agent,
AgentMetric,
TaskItem,
Ticket,
CreateTaskRequest,
CreateTicketRequest,
UpdateTicketRequest,
} from './types'
const BASE_URL = '/api/v1'
async function request<T>(path: string, options?: RequestInit): Promise<T> {
const res = await fetch(`${BASE_URL}${path}`, {
headers: { 'Content-Type': 'application/json', ...options?.headers },
...options,
})
if (!res.ok) {
const text = await res.text()
throw new Error(`HTTP ${res.status}: ${text}`)
}
if (res.status === 204) return undefined as T
return res.json() as Promise<T>
}
// Agents
export const agentsApi = {
list: () => request<Agent[]>('/agents'),
get: (id: string) => request<Agent>(`/agents/${id}`),
getMetrics: (id: string, limit = 100) =>
request<AgentMetric[]>(`/agents/${id}/metrics?limit=${limit}`),
}
// Tasks
export const tasksApi = {
create: (data: CreateTaskRequest) =>
request<TaskItem>('/tasks', { method: 'POST', body: JSON.stringify(data) }),
listForAgent: (agentId: string) =>
request<TaskItem[]>(`/tasks?agentId=${agentId}`),
}
// Tickets
export const ticketsApi = {
list: () => request<Ticket[]>('/tickets'),
get: (id: number) => request<Ticket>(`/tickets/${id}`),
create: (data: CreateTicketRequest) =>
request<Ticket>('/tickets', { method: 'POST', body: JSON.stringify(data) }),
update: (id: number, data: UpdateTicketRequest) =>
request<Ticket>(`/tickets/${id}`, { method: 'PUT', body: JSON.stringify(data) }),
}

95
Frontend/src/api/types.ts Normal file
View File

@@ -0,0 +1,95 @@
export type AgentStatus = 'Online' | 'Offline' | 'Degraded' | 'Pending'
export type OsType = 'Windows' | 'Linux'
export type TaskStatus = 'Pending' | 'InProgress' | 'Completed' | 'Failed' | 'Cancelled'
export type TaskType = 'Shell' | 'InstallSoftware' | 'UninstallSoftware' | 'UpdateAgent' | 'NetworkScan'
export type TicketStatus = 'Open' | 'InProgress' | 'Resolved' | 'Closed'
export type TicketPriority = 'Low' | 'Medium' | 'High' | 'Critical'
export type AlertSeverity = 'Info' | 'Warning' | 'Critical'
export interface Agent {
id: string
hostname: string
osType: OsType
osVersion: string
ipAddress: string
macAddress: string
agentVersion: string
status: AgentStatus
lastSeen: string
tags: string[]
enrolledAt: string
}
export interface DiskInfo {
mountPoint: string
totalBytes: number
freeBytes: number
filesystem: string
}
export interface NetworkInterfaceInfo {
name: string
ipAddress: string
macAddress: string
bytesSent: number
bytesRecv: number
}
export interface SystemMetrics {
cpuUsagePercent: number
memoryUsagePercent: number
memoryTotalBytes: number
memoryAvailableBytes: number
disks: DiskInfo[]
networkInterfaces: NetworkInterfaceInfo[]
uptimeSeconds: number
}
export interface AgentMetric {
id: number
agentId: string
timestamp: string
metrics: SystemMetrics
}
export interface TaskItem {
id: string
agentId: string
type: TaskType
status: TaskStatus
payload: Record<string, unknown> | null
result: Record<string, unknown> | null
createdAt: string
completedAt: string | null
}
export interface Ticket {
id: number
title: string
description: string
status: TicketStatus
priority: TicketPriority
agentId: string | null
createdAt: string
updatedAt: string
}
export interface CreateTaskRequest {
agentId: string
type: TaskType
payload?: Record<string, unknown>
}
export interface CreateTicketRequest {
title: string
description: string
priority: TicketPriority
agentId?: string
}
export interface UpdateTicketRequest {
title?: string
description?: string
status?: TicketStatus
priority?: TicketPriority
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

After

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 8.5 KiB

36
Frontend/src/index.css Normal file
View File

@@ -0,0 +1,36 @@
@import "tailwindcss";
@layer base {
:root {
--background: 222.2 84% 4.9%;
--foreground: 210 40% 98%;
--card: 222.2 84% 4.9%;
--card-foreground: 210 40% 98%;
--popover: 222.2 84% 4.9%;
--popover-foreground: 210 40% 98%;
--primary: 217.2 91.2% 59.8%;
--primary-foreground: 222.2 47.4% 11.2%;
--secondary: 217.2 32.6% 17.5%;
--secondary-foreground: 210 40% 98%;
--muted: 217.2 32.6% 17.5%;
--muted-foreground: 215 20.2% 65.1%;
--accent: 217.2 32.6% 17.5%;
--accent-foreground: 210 40% 98%;
--destructive: 0 62.8% 30.6%;
--destructive-foreground: 210 40% 98%;
--border: 217.2 32.6% 17.5%;
--input: 217.2 32.6% 17.5%;
--ring: 224.3 76.3% 48%;
--radius: 0.5rem;
}
}
@layer base {
* {
border-color: hsl(var(--border));
}
body {
background-color: hsl(var(--background));
color: hsl(var(--foreground));
}
}

View File

@@ -0,0 +1,6 @@
import { type ClassValue, clsx } from 'clsx'
import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

10
Frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,502 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
ChevronLeft,
Activity,
Database,
HardDrive,
Clock,
Terminal,
AlertCircle,
CheckCircle,
} from 'lucide-react'
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
} from 'recharts'
import { agentsApi, tasksApi } from '../api/client'
import type { TaskItem, TaskType } from '../api/types'
import { cn } from '../lib/utils'
interface AgentDetailPageProps {
agentId: string
onBack?: () => void
}
export function AgentDetailPage({ agentId, onBack }: AgentDetailPageProps) {
const [command, setCommand] = useState('')
const [isExecuting, setIsExecuting] = useState(false)
const [lastResult, setLastResult] = useState<TaskItem | null>(null)
const queryClient = useQueryClient()
// Fetch Agent Details
const { data: agent, isLoading: agentLoading } = useQuery({
queryKey: ['agent', agentId],
queryFn: () => agentsApi.get(agentId),
})
// Fetch Agent Metrics
const { data: metrics = [] } = useQuery({
queryKey: ['agentMetrics', agentId],
queryFn: () => agentsApi.getMetrics(agentId, 50),
})
// Fetch Agent Tasks
const { data: tasks = [] } = useQuery({
queryKey: ['agentTasks', agentId],
queryFn: () => tasksApi.listForAgent(agentId),
refetchInterval: 5000,
})
// Create Task Mutation
const createTaskMutation = useMutation({
mutationFn: (data: { agentId: string; type: TaskType; payload: Record<string, unknown> }) =>
tasksApi.create(data),
onSuccess: (task) => {
setLastResult(task)
setCommand('')
setIsExecuting(false)
// Invalidate tasks query to refetch
queryClient.invalidateQueries({ queryKey: ['agentTasks', agentId] })
},
onError: () => {
setIsExecuting(false)
},
})
if (agentLoading) {
return <div className="p-6 text-center">Agent-Details werden geladen...</div>
}
if (!agent) {
return <div className="p-6 text-center text-red-500">Agent nicht gefunden</div>
}
const handleExecuteCommand = async () => {
if (!command.trim()) return
setIsExecuting(true)
createTaskMutation.mutate({
agentId,
type: 'Shell' as TaskType,
payload: { command: command.trim() },
})
}
// Calculate metrics from latest data
const latestMetric = metrics.length > 0 ? metrics[metrics.length - 1] : null
const cpuUsage = latestMetric?.metrics.cpuUsagePercent ?? 0
const memoryUsage = latestMetric
? ((latestMetric.metrics.memoryTotalBytes - latestMetric.metrics.memoryAvailableBytes) /
latestMetric.metrics.memoryTotalBytes) *
100
: 0
const memoryTotalGB = latestMetric
? (latestMetric.metrics.memoryTotalBytes / (1024 * 1024 * 1024)).toFixed(1)
: '0'
const uptimeSeconds = latestMetric?.metrics.uptimeSeconds ?? 0
const uptimeFormatted = formatUptime(uptimeSeconds)
const isOnline = agent.status === 'Online'
// Format chart data
const chartData = metrics
.slice(0, 50)
.map((metric) => ({
time: new Date(metric.timestamp).toLocaleTimeString('de-DE', {
hour: '2-digit',
minute: '2-digit',
}),
cpu: metric.metrics.cpuUsagePercent,
memory:
((metric.metrics.memoryTotalBytes - metric.metrics.memoryAvailableBytes) /
metric.metrics.memoryTotalBytes) *
100,
}))
// Get disks
const disks = latestMetric?.metrics.disks ?? []
// Get last 10 tasks
const lastTasks = tasks.slice(0, 10)
return (
<div className="min-h-screen bg-background p-6">
{/* Header */}
<div className="mb-8">
<button
onClick={onBack}
className="mb-4 inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<ChevronLeft size={18} />
Zurück
</button>
<div className="flex items-start justify-between">
<div>
<h1 className="text-3xl font-bold text-foreground">{agent.hostname}</h1>
<div className="mt-3 flex flex-wrap gap-4 text-sm text-muted-foreground">
<span>IP: {agent.ipAddress}</span>
<span>OS: {agent.osType} {agent.osVersion}</span>
<span>Agent: v{agent.agentVersion}</span>
</div>
</div>
<div className="flex items-center gap-2">
<span
className={cn(
'inline-block h-3 w-3 rounded-full',
isOnline ? 'bg-green-500' : 'bg-red-500'
)}
/>
<span className={cn('text-sm font-medium', isOnline ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400')}>
{agent.status}
</span>
</div>
</div>
</div>
{/* Info Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
<InfoCard
title="CPU-Auslastung"
value={`${cpuUsage.toFixed(1)}%`}
icon={Activity}
/>
<InfoCard
title="RAM-Auslastung"
value={`${memoryUsage.toFixed(1)}%`}
icon={Database}
/>
<InfoCard
title="RAM gesamt"
value={`${memoryTotalGB} GB`}
icon={HardDrive}
/>
<InfoCard
title="Uptime"
value={uptimeFormatted}
icon={Clock}
/>
</div>
{/* Charts */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
{/* CPU Chart */}
<div className="bg-card border border-border rounded-lg p-4">
<h3 className="font-semibold text-foreground mb-4">CPU-Auslastung</h3>
{chartData.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<LineChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
<XAxis
dataKey="time"
stroke="var(--color-muted-foreground)"
style={{ fontSize: '12px' }}
/>
<YAxis
stroke="var(--color-muted-foreground)"
domain={[0, 100]}
style={{ fontSize: '12px' }}
/>
<Tooltip
contentStyle={{
backgroundColor: 'var(--color-background)',
border: '1px solid var(--color-border)',
borderRadius: '4px',
}}
formatter={(value: unknown) => typeof value === 'number' ? `${value.toFixed(1)}%` : ''}
/>
<Line
type="monotone"
dataKey="cpu"
stroke="#3b82f6"
dot={false}
strokeWidth={2}
/>
</LineChart>
</ResponsiveContainer>
) : (
<div className="flex items-center justify-center h-[250px] text-muted-foreground">
Keine Daten verfügbar
</div>
)}
</div>
{/* RAM Chart */}
<div className="bg-card border border-border rounded-lg p-4">
<h3 className="font-semibold text-foreground mb-4">Arbeitsspeicher-Auslastung</h3>
{chartData.length > 0 ? (
<ResponsiveContainer width="100%" height={250}>
<LineChart data={chartData}>
<CartesianGrid strokeDasharray="3 3" stroke="var(--color-border)" />
<XAxis
dataKey="time"
stroke="var(--color-muted-foreground)"
style={{ fontSize: '12px' }}
/>
<YAxis
stroke="var(--color-muted-foreground)"
domain={[0, 100]}
style={{ fontSize: '12px' }}
/>
<Tooltip
contentStyle={{
backgroundColor: 'var(--color-background)',
border: '1px solid var(--color-border)',
borderRadius: '4px',
}}
formatter={(value: unknown) => typeof value === 'number' ? `${value.toFixed(1)}%` : ''}
/>
<Line
type="monotone"
dataKey="memory"
stroke="#22c55e"
dot={false}
strokeWidth={2}
/>
</LineChart>
</ResponsiveContainer>
) : (
<div className="flex items-center justify-center h-[250px] text-muted-foreground">
Keine Daten verfügbar
</div>
)}
</div>
</div>
{/* Disk Display */}
{disks.length > 0 && (
<div className="mb-8">
<h3 className="text-lg font-semibold text-foreground mb-4">Festplattenspeicher</h3>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{disks.map((disk, idx) => {
const usedBytes = disk.totalBytes - disk.freeBytes
const usagePercent = (usedBytes / disk.totalBytes) * 100
const usedGB = (usedBytes / (1024 * 1024 * 1024)).toFixed(1)
const totalGB = (disk.totalBytes / (1024 * 1024 * 1024)).toFixed(1)
let barColor = 'bg-green-500'
if (usagePercent >= 90) {
barColor = 'bg-red-500'
} else if (usagePercent >= 70) {
barColor = 'bg-yellow-500'
}
return (
<div
key={idx}
className="bg-card border border-border rounded-lg p-4"
>
<div className="mb-2 text-sm font-medium text-foreground">
{disk.mountPoint}
</div>
<div className="mb-2 h-2 w-full bg-muted rounded-full overflow-hidden">
<div
className={cn('h-full transition-all', barColor)}
style={{ width: `${usagePercent}%` }}
/>
</div>
<div className="text-xs text-muted-foreground">
{usedGB} GB / {totalGB} GB ({usagePercent.toFixed(0)}%)
</div>
</div>
)
})}
</div>
</div>
)}
{/* Shell Command Executor */}
<div className="mb-8 bg-card border border-border rounded-lg p-6">
<h3 className="text-lg font-semibold text-foreground mb-4 flex items-center gap-2">
<Terminal size={20} />
Befehl ausführen
</h3>
<div className="mb-4">
<textarea
value={command}
onChange={(e) => setCommand(e.target.value)}
placeholder="Befehl eingeben..."
className="w-full h-24 px-3 py-2 bg-background border border-border rounded-md text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary resize-none"
disabled={isExecuting}
/>
</div>
<button
onClick={handleExecuteCommand}
disabled={isExecuting || !command.trim()}
className="inline-flex items-center gap-2 px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
>
<Terminal size={16} />
{isExecuting ? 'Wird ausgeführt...' : 'Ausführen'}
</button>
{/* Result Display */}
{lastResult && (
<div
className={cn(
'mt-4 p-4 rounded-md border-2',
lastResult.result?.success
? 'border-green-500 bg-green-500/5'
: 'border-red-500 bg-red-500/5'
)}
>
{lastResult.result ? (
<>
<div className="flex items-center gap-2 mb-3">
{lastResult.result.success ? (
<>
<CheckCircle size={18} className="text-green-600 dark:text-green-400" />
<span className="font-semibold text-green-600 dark:text-green-400">
Erfolgreich ausgeführt
</span>
</>
) : (
<>
<AlertCircle size={18} className="text-red-600 dark:text-red-400" />
<span className="font-semibold text-red-600 dark:text-red-400">
Fehler bei Ausführung
</span>
</>
)}
</div>
{lastResult.result.stdout && (
<div className="mb-3">
<div className="text-xs font-semibold text-muted-foreground mb-1">
Output:
</div>
<pre className="bg-background p-3 rounded text-xs overflow-auto max-h-40 text-muted-foreground">
{String(lastResult.result.stdout ?? '')}
</pre>
</div>
)}
{lastResult.result.stderr && (
<div className="mb-3">
<div className="text-xs font-semibold text-red-600 dark:text-red-400 mb-1">
Error:
</div>
<pre className="bg-background p-3 rounded text-xs overflow-auto max-h-40 text-red-600 dark:text-red-400">
{String(lastResult.result.stderr ?? '')}
</pre>
</div>
)}
<div className="text-xs text-muted-foreground">
Exit Code: {String(lastResult.result.exitCode ?? '-')}
</div>
</>
) : (
<div className="flex items-center gap-2 text-muted-foreground">
<Terminal size={16} />
<span>
Befehl gesendet. Er wird beim nächsten Heartbeat ausgeführt.
</span>
</div>
)}
</div>
)}
</div>
{/* Recent Tasks */}
<div>
<h3 className="text-lg font-semibold text-foreground mb-4">Letzte Ausführungen</h3>
{lastTasks.length > 0 ? (
<div className="bg-card border border-border rounded-lg overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-muted border-b border-border">
<tr>
<th className="px-4 py-3 text-left font-semibold text-foreground">
Erstellt am
</th>
<th className="px-4 py-3 text-left font-semibold text-foreground">Typ</th>
<th className="px-4 py-3 text-left font-semibold text-foreground">Status</th>
<th className="px-4 py-3 text-left font-semibold text-foreground">
Exit Code
</th>
</tr>
</thead>
<tbody>
{lastTasks.map((task) => (
<tr key={task.id} className="border-b border-border hover:bg-muted/50">
<td className="px-4 py-3 text-muted-foreground">
{new Date(task.createdAt).toLocaleString('de-DE')}
</td>
<td className="px-4 py-3 text-foreground">{task.type}</td>
<td className="px-4 py-3">
<span
className={cn(
'inline-flex items-center gap-1 text-xs font-semibold px-2 py-1 rounded',
task.status === 'Completed'
? 'bg-green-500/20 text-green-600 dark:text-green-400'
: task.status === 'Failed'
? 'bg-red-500/20 text-red-600 dark:text-red-400'
: 'bg-yellow-500/20 text-yellow-600 dark:text-yellow-400'
)}
>
{task.status}
</span>
</td>
<td className="px-4 py-3 text-muted-foreground">
{task.result ? String(task.result.exitCode ?? '-') : '-'}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
) : (
<div className="bg-card border border-border rounded-lg p-6 text-center text-muted-foreground">
Keine Aufgaben verfügbar
</div>
)}
</div>
</div>
)
}
// Helper Components
interface InfoCardProps {
title: string
value: string
icon: React.ComponentType<{ size?: number; className?: string }>
}
function InfoCard({ title, value, icon: Icon }: InfoCardProps) {
return (
<div className="bg-card border border-border rounded-lg p-4">
<div className="flex items-center justify-between">
<div>
<div className="text-xs text-muted-foreground font-medium uppercase tracking-wide">
{title}
</div>
<div className="mt-2 text-2xl font-bold text-foreground">{value}</div>
</div>
<Icon size={24} className="text-muted-foreground" />
</div>
</div>
)
}
// Utility Functions
function formatUptime(seconds: number): string {
const days = Math.floor(seconds / (24 * 3600))
const hours = Math.floor((seconds % (24 * 3600)) / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const parts = []
if (days > 0) parts.push(`${days}d`)
if (hours > 0) parts.push(`${hours}h`)
if (minutes > 0) parts.push(`${minutes}m`)
return parts.length > 0 ? parts.join(' ') : '0m'
}

View File

@@ -0,0 +1,355 @@
import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import {
Monitor,
Server,
CheckCircle,
XCircle,
AlertCircle,
Search,
ChevronUp,
ChevronDown,
} from 'lucide-react'
import { agentsApi, ticketsApi } from '../api/client'
import type { Agent } from '../api/types'
import { cn } from '../lib/utils'
interface DashboardPageProps {
onSelectAgent?: (agentId: string) => void
}
// Helper function for relative time formatting
function formatRelativeTime(dateString: string): string {
const now = new Date()
const date = new Date(dateString)
const diffMs = now.getTime() - date.getTime()
// Calculate different time units
const diffSeconds = Math.floor(diffMs / 1000)
const diffMinutes = Math.floor(diffSeconds / 60)
const diffHours = Math.floor(diffMinutes / 60)
const diffDays = Math.floor(diffHours / 24)
if (diffSeconds < 60) {
return 'gerade eben'
}
if (diffMinutes < 60) {
return `vor ${diffMinutes} Min.`
}
if (diffHours < 24) {
return `vor ${diffHours} Std.`
}
return `vor ${diffDays} Tagen`
}
// Stat Card Component
function StatCard({
label,
value,
icon: Icon,
iconColor,
}: {
label: string
value: number | string
icon: React.ReactNode
iconColor: string
}) {
return (
<div className="bg-card border border-border rounded-lg p-5 flex items-start gap-4">
<div className={cn('mt-1', iconColor)}>{Icon}</div>
<div className="flex-1">
<div className="text-3xl font-bold text-foreground">{value}</div>
<div className="text-sm text-muted-foreground mt-1">{label}</div>
</div>
</div>
)
}
// Status Badge Component
function StatusBadge({ status }: { status: string }) {
const statusConfig = {
Online: { bg: 'bg-green-500/20', text: 'text-green-500', label: 'Online' },
Offline: { bg: 'bg-red-500/20', text: 'text-red-500', label: 'Offline' },
Degraded: { bg: 'bg-yellow-500/20', text: 'text-yellow-500', label: 'Beeinträchtigt' },
Pending: { bg: 'bg-gray-500/20', text: 'text-gray-500', label: 'Ausstehend' },
}
const config = statusConfig[status as keyof typeof statusConfig] || statusConfig.Pending
return (
<div className={cn('px-3 py-1 rounded-full text-xs font-medium', config.bg, config.text)}>
{config.label}
</div>
)
}
// Loading Skeleton Component
function TableSkeletonRow() {
return (
<tr className="border-b border-border hover:bg-card/50 transition-colors">
{Array(6)
.fill(null)
.map((_, i) => (
<td key={i} className="px-4 py-3">
<div className="h-4 bg-muted-foreground/10 rounded animate-pulse"></div>
</td>
))}
</tr>
)
}
export function DashboardPage({ onSelectAgent }: DashboardPageProps) {
const [searchTerm, setSearchTerm] = useState('')
const [sortColumn, setSortColumn] = useState<keyof Agent>('hostname')
const [sortDirection, setSortDirection] = useState<'asc' | 'desc'>('asc')
// Fetch agents data
const {
data: agents = [],
isLoading: agentsLoading,
error: agentsError,
} = useQuery({
queryKey: ['agents'],
queryFn: () => agentsApi.list(),
staleTime: 30000,
})
// Fetch tickets data
const {
data: tickets = [],
} = useQuery({
queryKey: ['tickets'],
queryFn: () => ticketsApi.list(),
staleTime: 30000,
})
// Calculate statistics
const stats = useMemo(() => {
const totalAgents = agents.length
const onlineAgents = agents.filter((a) => a.status === 'Online').length
const offlineAgents = agents.filter((a) => a.status === 'Offline').length
const openTickets = tickets.filter(
(t) => t.status === 'Open' || t.status === 'InProgress'
).length
return { totalAgents, onlineAgents, offlineAgents, openTickets }
}, [agents, tickets])
// Filter and sort agents
const filteredAndSortedAgents = useMemo(() => {
let filtered = agents.filter((agent) => {
const searchLower = searchTerm.toLowerCase()
return (
agent.hostname.toLowerCase().includes(searchLower) ||
agent.ipAddress.toLowerCase().includes(searchLower) ||
agent.osVersion.toLowerCase().includes(searchLower)
)
})
filtered.sort((a, b) => {
let aVal = a[sortColumn]
let bVal = b[sortColumn]
if (typeof aVal === 'string') {
aVal = aVal.toLowerCase()
bVal = (bVal as string).toLowerCase()
}
if (aVal < bVal) return sortDirection === 'asc' ? -1 : 1
if (aVal > bVal) return sortDirection === 'asc' ? 1 : -1
return 0
})
return filtered
}, [agents, searchTerm, sortColumn, sortDirection])
// Handle column header click for sorting
const handleSort = (column: keyof Agent) => {
if (sortColumn === column) {
setSortDirection(sortDirection === 'asc' ? 'desc' : 'asc')
} else {
setSortColumn(column)
setSortDirection('asc')
}
}
// Render sort indicator
const SortIndicator = ({ column }: { column: keyof Agent }) => {
if (sortColumn !== column) return null
return sortDirection === 'asc' ? (
<ChevronUp className="w-4 h-4 inline ml-1" />
) : (
<ChevronDown className="w-4 h-4 inline ml-1" />
)
}
// Get OS icon
const getOsIcon = (osType: string) => {
if (osType === 'Windows') {
return <Monitor className="w-4 h-4 text-blue-500" />
}
return <Server className="w-4 h-4 text-orange-500" />
}
return (
<div className="space-y-6 p-6">
{/* Header */}
<div>
<h1 className="text-3xl font-bold text-foreground">Dashboard</h1>
<p className="text-muted-foreground mt-1">
Überwachen Sie Ihre Geräte und Tickets auf einen Blick
</p>
</div>
{/* Statistics Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<StatCard
label="Gesamt Agents"
value={stats.totalAgents}
icon={<Monitor className="w-6 h-6 text-primary" />}
iconColor="text-primary"
/>
<StatCard
label="Online"
value={stats.onlineAgents}
icon={<CheckCircle className="w-6 h-6 text-green-500" />}
iconColor="text-green-500"
/>
<StatCard
label="Offline"
value={stats.offlineAgents}
icon={<XCircle className="w-6 h-6 text-red-500" />}
iconColor="text-red-500"
/>
<StatCard
label="Offene Tickets"
value={stats.openTickets}
icon={<AlertCircle className="w-6 h-6 text-yellow-500" />}
iconColor="text-yellow-500"
/>
</div>
{/* Agents Table Section */}
<div className="bg-card border border-border rounded-lg p-6">
{/* Header with Search */}
<div className="flex items-center justify-between mb-6">
<h2 className="text-xl font-bold text-foreground">Alle Geräte</h2>
<div className="relative w-64">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-muted-foreground" />
<input
type="text"
placeholder="Nach Hostname, IP oder OS suchen..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pl-10 pr-4 py-2 bg-background border border-border rounded-lg text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
/>
</div>
</div>
{/* Error State */}
{agentsError && (
<div className="bg-red-500/10 border border-red-500/30 rounded-lg p-4 text-red-500 mb-4">
<p className="font-medium">Fehler beim Laden der Geräte</p>
<p className="text-sm mt-1">
{agentsError instanceof Error ? agentsError.message : 'Ein unbekannter Fehler ist aufgetreten'}
</p>
</div>
)}
{/* Table */}
<div className="overflow-x-auto">
<table className="w-full">
<thead>
<tr className="border-b border-border bg-muted/30">
<th
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort('hostname')}
>
Hostname <SortIndicator column="hostname" />
</th>
<th
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort('osVersion')}
>
OS Version <SortIndicator column="osVersion" />
</th>
<th
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort('ipAddress')}
>
IP-Adresse <SortIndicator column="ipAddress" />
</th>
<th className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground">
Status
</th>
<th
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort('lastSeen')}
>
Zuletzt gesehen <SortIndicator column="lastSeen" />
</th>
<th
className="px-4 py-3 text-left text-sm font-semibold text-muted-foreground cursor-pointer hover:text-foreground transition-colors"
onClick={() => handleSort('agentVersion')}
>
Version <SortIndicator column="agentVersion" />
</th>
</tr>
</thead>
<tbody>
{agentsLoading ? (
Array(5)
.fill(null)
.map((_, i) => <TableSkeletonRow key={i} />)
) : filteredAndSortedAgents.length === 0 ? (
<tr className="border-b border-border">
<td colSpan={6} className="px-4 py-8 text-center text-muted-foreground">
{searchTerm
? 'Keine Geräte gefunden'
: 'Keine Geräte vorhanden'}
</td>
</tr>
) : (
filteredAndSortedAgents.map((agent) => (
<tr
key={agent.id}
className={cn(
'border-b border-border hover:bg-card/50 transition-colors',
onSelectAgent && 'cursor-pointer'
)}
onClick={() => onSelectAgent?.(agent.id)}
>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
{getOsIcon(agent.osType)}
<span className="text-foreground font-medium">{agent.hostname}</span>
</div>
</td>
<td className="px-4 py-3 text-foreground">{agent.osVersion}</td>
<td className="px-4 py-3 text-foreground font-mono text-sm">
{agent.ipAddress}
</td>
<td className="px-4 py-3">
<StatusBadge status={agent.status} />
</td>
<td className="px-4 py-3 text-foreground">
{formatRelativeTime(agent.lastSeen)}
</td>
<td className="px-4 py-3 text-foreground text-sm">{agent.agentVersion}</td>
</tr>
))
)}
</tbody>
</table>
</div>
{/* Results Count */}
{!agentsLoading && filteredAndSortedAgents.length > 0 && (
<div className="mt-4 text-sm text-muted-foreground">
{filteredAndSortedAgents.length} von {agents.length} Geräten angezeigt
</div>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,625 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Plus, Edit, X, ChevronUp, ChevronDown } from 'lucide-react'
import { ticketsApi } from '../api/client'
import type { Ticket, TicketStatus, TicketPriority } from '../api/types'
import { cn } from '../lib/utils'
type SortField = 'id' | 'title' | 'status' | 'priority' | 'createdAt'
type SortOrder = 'asc' | 'desc'
function formatDate(dateString: string): string {
return new Date(dateString).toLocaleDateString('de-DE', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
}
function getStatusColor(status: TicketStatus): string {
const colors = {
Open: 'bg-blue-500/20 text-blue-400 border border-blue-500/30',
InProgress: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30',
Resolved: 'bg-green-500/20 text-green-400 border border-green-500/30',
Closed: 'bg-gray-500/20 text-gray-400 border border-gray-500/30',
}
return colors[status]
}
function getPriorityColor(priority: TicketPriority): string {
const colors = {
Critical: 'bg-red-500/20 text-red-400 border border-red-500/30',
High: 'bg-orange-500/20 text-orange-400 border border-orange-500/30',
Medium: 'bg-yellow-500/20 text-yellow-400 border border-yellow-500/30',
Low: 'bg-gray-500/20 text-gray-400 border border-gray-500/30',
}
return colors[priority]
}
function getStatusLabel(status: TicketStatus): string {
const labels = {
Open: 'Offen',
InProgress: 'In Bearbeitung',
Resolved: 'Gelöst',
Closed: 'Geschlossen',
}
return labels[status]
}
function getPriorityLabel(priority: TicketPriority): string {
const labels = {
Critical: 'Kritisch',
High: 'Hoch',
Medium: 'Mittel',
Low: 'Niedrig',
}
return labels[priority]
}
interface CreateTicketFormState {
title: string
description: string
priority: TicketPriority
agentId?: string
}
interface EditTicketFormState {
title: string
description: string
status: TicketStatus
priority: TicketPriority
}
export default function TicketsPage() {
const queryClient = useQueryClient()
// State für Filter und Sortierung
const [statusFilter, setStatusFilter] = useState<TicketStatus | 'All'>('All')
const [priorityFilter, setPriorityFilter] = useState<TicketPriority | 'All'>('All')
const [searchTerm, setSearchTerm] = useState('')
const [sortField, setSortField] = useState<SortField>('createdAt')
const [sortOrder, setSortOrder] = useState<SortOrder>('desc')
// State für Modals
const [showCreateModal, setShowCreateModal] = useState(false)
const [showDetailModal, setShowDetailModal] = useState(false)
const [showEditModal, setShowEditModal] = useState(false)
const [selectedTicketId, setSelectedTicketId] = useState<number | null>(null)
// State für Create-Formular
const [createForm, setCreateForm] = useState<CreateTicketFormState>({
title: '',
description: '',
priority: 'Medium',
})
// State für Edit-Formular
const [editForm, setEditForm] = useState<EditTicketFormState>({
title: '',
description: '',
status: 'Open',
priority: 'Medium',
})
// Queries
const { data: tickets = [], isLoading, error } = useQuery({
queryKey: ['tickets'],
queryFn: () => ticketsApi.list(),
})
const selectedTicket = tickets.find((t) => t.id === selectedTicketId)
// Mutations
const createMutation = useMutation({
mutationFn: (data: CreateTicketFormState) => ticketsApi.create(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tickets'] })
setShowCreateModal(false)
setCreateForm({
title: '',
description: '',
priority: 'Medium',
})
},
})
const updateMutation = useMutation({
mutationFn: (data: EditTicketFormState) => {
if (!selectedTicketId) throw new Error('No ticket selected')
return ticketsApi.update(selectedTicketId, data)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tickets'] })
setShowEditModal(false)
setShowDetailModal(false)
setSelectedTicketId(null)
},
})
// Filterte und sortierte Tickets
let filteredTickets = tickets.filter((ticket) => {
const statusMatch = statusFilter === 'All' || ticket.status === statusFilter
const priorityMatch = priorityFilter === 'All' || ticket.priority === priorityFilter
const searchMatch =
searchTerm === '' || ticket.title.toLowerCase().includes(searchTerm.toLowerCase())
return statusMatch && priorityMatch && searchMatch
})
filteredTickets = filteredTickets.sort((a, b) => {
let aVal: any = a[sortField]
let bVal: any = b[sortField]
if (sortField === 'createdAt' || sortField === 'id') {
aVal = new Date(aVal).getTime()
bVal = new Date(bVal).getTime()
} else if (typeof aVal === 'string') {
aVal = aVal.toLowerCase()
bVal = bVal.toLowerCase()
}
if (aVal < bVal) return sortOrder === 'asc' ? -1 : 1
if (aVal > bVal) return sortOrder === 'asc' ? 1 : -1
return 0
})
const handleSort = (field: SortField) => {
if (sortField === field) {
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc')
} else {
setSortField(field)
setSortOrder('asc')
}
}
const handleCreateSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!createForm.title.trim()) return
createMutation.mutate(createForm)
}
const handleEditSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!editForm.title.trim()) return
updateMutation.mutate(editForm)
}
const openDetail = (ticketId: number) => {
setSelectedTicketId(ticketId)
setShowDetailModal(true)
}
const openEdit = (ticket: Ticket) => {
setSelectedTicketId(ticket.id)
setEditForm({
title: ticket.title,
description: ticket.description,
status: ticket.status,
priority: ticket.priority,
})
setShowDetailModal(false)
setShowEditModal(true)
}
const SortButton = ({ field, label }: { field: SortField; label: string }) => (
<button
onClick={() => handleSort(field)}
className="flex items-center gap-1 hover:text-primary transition-colors"
>
{label}
{sortField === field &&
(sortOrder === 'asc' ? (
<ChevronUp size={16} />
) : (
<ChevronDown size={16} />
))}
</button>
)
return (
<div className="space-y-6 p-6">
{/* Header */}
<div className="flex items-center justify-between">
<h1 className="text-3xl font-bold">Tickets</h1>
<button
onClick={() => setShowCreateModal(true)}
className="flex items-center gap-2 bg-primary text-primary-foreground px-4 py-2 rounded-lg hover:opacity-90 transition-opacity"
>
<Plus size={20} />
Neues Ticket
</button>
</div>
{/* Filter-Leiste */}
<div className="space-y-4 bg-card border border-border rounded-lg p-4">
{/* Status-Filter */}
<div className="flex flex-wrap gap-2">
{['All', 'Open', 'InProgress', 'Resolved', 'Closed'].map((status) => (
<button
key={status}
onClick={() => setStatusFilter(status as TicketStatus | 'All')}
className={cn(
'px-3 py-1 rounded-full text-sm font-medium transition-colors',
statusFilter === status
? 'bg-primary text-primary-foreground'
: 'bg-muted text-muted-foreground hover:bg-muted/80'
)}
>
{status === 'All'
? 'Alle'
: status === 'Open'
? 'Offen'
: status === 'InProgress'
? 'In Bearbeitung'
: status === 'Resolved'
? 'Gelöst'
: 'Geschlossen'}
</button>
))}
</div>
{/* Prioritäts-Filter und Suchfeld */}
<div className="flex flex-col sm:flex-row gap-4">
<select
value={priorityFilter}
onChange={(e) => setPriorityFilter(e.target.value as TicketPriority | 'All')}
className="px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="All">Alle Prioritäten</option>
<option value="Critical">Kritisch</option>
<option value="High">Hoch</option>
<option value="Medium">Mittel</option>
<option value="Low">Niedrig</option>
</select>
<input
type="text"
placeholder="Nach Titel suchen..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="px-3 py-2 bg-background border border-border rounded-lg text-sm flex-1 focus:outline-none focus:ring-2 focus:ring-primary"
/>
</div>
</div>
{/* Ticket-Tabelle */}
<div className="bg-card border border-border rounded-lg overflow-hidden">
{isLoading ? (
<div className="p-8 text-center text-muted-foreground">Tickets werden geladen...</div>
) : error ? (
<div className="p-8 text-center text-red-400">Fehler beim Laden der Tickets</div>
) : filteredTickets.length === 0 ? (
<div className="p-8 text-center text-muted-foreground">Keine Tickets gefunden</div>
) : (
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-muted border-b border-border">
<tr>
<th className="px-6 py-3 text-left text-sm font-semibold">
<SortButton field="id" label="#" />
</th>
<th className="px-6 py-3 text-left text-sm font-semibold">
<SortButton field="title" label="Titel" />
</th>
<th className="px-6 py-3 text-left text-sm font-semibold">
<SortButton field="status" label="Status" />
</th>
<th className="px-6 py-3 text-left text-sm font-semibold">
<SortButton field="priority" label="Priorität" />
</th>
<th className="px-6 py-3 text-left text-sm font-semibold">
<SortButton field="createdAt" label="Erstellt" />
</th>
<th className="px-6 py-3 text-left text-sm font-semibold">Aktionen</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{filteredTickets.map((ticket) => (
<tr
key={ticket.id}
className="hover:bg-muted/50 transition-colors cursor-pointer"
>
<td
className="px-6 py-4 text-sm font-medium"
onClick={() => openDetail(ticket.id)}
>
#{ticket.id}
</td>
<td
className="px-6 py-4 text-sm font-medium text-primary hover:underline"
onClick={() => openDetail(ticket.id)}
>
{ticket.title}
</td>
<td className="px-6 py-4">
<span className={cn('px-2 py-1 rounded text-xs font-semibold', getStatusColor(ticket.status))}>
{getStatusLabel(ticket.status)}
</span>
</td>
<td className="px-6 py-4">
<span className={cn('px-2 py-1 rounded text-xs font-semibold', getPriorityColor(ticket.priority))}>
{getPriorityLabel(ticket.priority)}
</span>
</td>
<td className="px-6 py-4 text-sm">{formatDate(ticket.createdAt)}</td>
<td className="px-6 py-4">
<button
onClick={() => openEdit(ticket)}
className="p-1 hover:bg-muted rounded transition-colors"
title="Bearbeiten"
>
<Edit size={18} className="text-muted-foreground hover:text-primary" />
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
{/* Create Modal */}
{showCreateModal && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-card border border-border rounded-lg p-6 w-full max-w-md">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-bold">Neues Ticket</h2>
<button
onClick={() => setShowCreateModal(false)}
className="p-1 hover:bg-muted rounded transition-colors"
>
<X size={20} />
</button>
</div>
<form onSubmit={handleCreateSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">Titel *</label>
<input
type="text"
required
value={createForm.title}
onChange={(e) =>
setCreateForm({ ...createForm, title: e.target.value })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="Ticket-Titel"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Beschreibung</label>
<textarea
value={createForm.description}
onChange={(e) =>
setCreateForm({ ...createForm, description: e.target.value })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
placeholder="Beschreibung..."
rows={4}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Priorität</label>
<select
value={createForm.priority}
onChange={(e) =>
setCreateForm({ ...createForm, priority: e.target.value as TicketPriority })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="Low">Niedrig</option>
<option value="Medium">Mittel</option>
<option value="High">Hoch</option>
<option value="Critical">Kritisch</option>
</select>
</div>
<div className="flex gap-2 justify-end pt-4">
<button
type="button"
onClick={() => setShowCreateModal(false)}
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
>
Abbrechen
</button>
<button
type="submit"
disabled={createMutation.isPending}
className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50"
>
{createMutation.isPending ? 'Speichert...' : 'Speichern'}
</button>
</div>
</form>
</div>
</div>
)}
{/* Detail Modal */}
{showDetailModal && selectedTicket && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-card border border-border rounded-lg p-6 w-full max-w-md">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-bold">Ticket-Details</h2>
<button
onClick={() => {
setShowDetailModal(false)
setSelectedTicketId(null)
}}
className="p-1 hover:bg-muted rounded transition-colors"
>
<X size={20} />
</button>
</div>
<div className="space-y-3 mb-6">
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase">ID</p>
<p className="text-sm">{selectedTicket.id}</p>
</div>
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase">Titel</p>
<p className="text-sm font-medium">{selectedTicket.title}</p>
</div>
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase">Beschreibung</p>
<p className="text-sm">{selectedTicket.description || '-'}</p>
</div>
<div className="flex gap-4">
<div className="flex-1">
<p className="text-xs font-semibold text-muted-foreground uppercase">Status</p>
<span className={cn('inline-block px-2 py-1 rounded text-xs font-semibold mt-1', getStatusColor(selectedTicket.status))}>
{getStatusLabel(selectedTicket.status)}
</span>
</div>
<div className="flex-1">
<p className="text-xs font-semibold text-muted-foreground uppercase">Priorität</p>
<span className={cn('inline-block px-2 py-1 rounded text-xs font-semibold mt-1', getPriorityColor(selectedTicket.priority))}>
{getPriorityLabel(selectedTicket.priority)}
</span>
</div>
</div>
{selectedTicket.agentId && (
<div>
<p className="text-xs font-semibold text-muted-foreground uppercase">Agent</p>
<p className="text-sm">{selectedTicket.agentId}</p>
</div>
)}
<div className="flex gap-4 text-xs">
<div>
<p className="font-semibold text-muted-foreground">Erstellt</p>
<p>{formatDate(selectedTicket.createdAt)}</p>
</div>
<div>
<p className="font-semibold text-muted-foreground">Aktualisiert</p>
<p>{formatDate(selectedTicket.updatedAt)}</p>
</div>
</div>
</div>
<div className="flex gap-2 justify-end">
<button
onClick={() => {
setShowDetailModal(false)
setSelectedTicketId(null)
}}
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
>
Schließen
</button>
<button
onClick={() => openEdit(selectedTicket)}
className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity flex items-center gap-2"
>
<Edit size={16} />
Bearbeiten
</button>
</div>
</div>
</div>
)}
{/* Edit Modal */}
{showEditModal && selectedTicket && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-card border border-border rounded-lg p-6 w-full max-w-md">
<div className="flex items-center justify-between mb-4">
<h2 className="text-xl font-bold">Ticket bearbeiten</h2>
<button
onClick={() => setShowEditModal(false)}
className="p-1 hover:bg-muted rounded transition-colors"
>
<X size={20} />
</button>
</div>
<form onSubmit={handleEditSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium mb-1">Titel *</label>
<input
type="text"
required
value={editForm.title}
onChange={(e) =>
setEditForm({ ...editForm, title: e.target.value })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
placeholder="Ticket-Titel"
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Beschreibung</label>
<textarea
value={editForm.description}
onChange={(e) =>
setEditForm({ ...editForm, description: e.target.value })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
placeholder="Beschreibung..."
rows={4}
/>
</div>
<div>
<label className="block text-sm font-medium mb-1">Status</label>
<select
value={editForm.status}
onChange={(e) =>
setEditForm({ ...editForm, status: e.target.value as TicketStatus })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="Open">Offen</option>
<option value="InProgress">In Bearbeitung</option>
<option value="Resolved">Gelöst</option>
<option value="Closed">Geschlossen</option>
</select>
</div>
<div>
<label className="block text-sm font-medium mb-1">Priorität</label>
<select
value={editForm.priority}
onChange={(e) =>
setEditForm({ ...editForm, priority: e.target.value as TicketPriority })
}
className="w-full px-3 py-2 bg-background border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="Low">Niedrig</option>
<option value="Medium">Mittel</option>
<option value="High">Hoch</option>
<option value="Critical">Kritisch</option>
</select>
</div>
<div className="flex gap-2 justify-end pt-4">
<button
type="button"
onClick={() => setShowEditModal(false)}
className="px-4 py-2 text-sm font-medium rounded-lg border border-border hover:bg-muted transition-colors"
>
Abbrechen
</button>
<button
type="submit"
disabled={updateMutation.isPending}
className="px-4 py-2 text-sm font-medium bg-primary text-primary-foreground rounded-lg hover:opacity-90 transition-opacity disabled:opacity-50"
>
{updateMutation.isPending ? 'Speichert...' : 'Speichern'}
</button>
</div>
</form>
</div>
</div>
)}
</div>
)
}