import { useEffect, useState } from 'react'; import { ApiError, objectId, page, pretty, record, request, session, tenantPath, type RecordValue, type Session, type Tenant } from './api'; import { AdminControl } from './management'; import { allowed } from './safety'; import { CatalogCheckNotice } from './catalog-check'; import { devicePlatform } from './script-catalog'; import { DeviceInventoryPanels, systemDetails } from './device-inventory'; import { DeviceCustomerTransfer } from './device-customer-transfer'; import { HypervisorAssignment, HypervisorLabel } from './device-hypervisor'; import { ErrorBox, errorText, useResource } from './resource'; import { NavIcon, orderDetailRoute } from './navigation'; import { orderTitle, Status } from './order-presentation'; import { RecoveryReview, recoveryAsset, recoveryTenant } from './recovery-review'; import { EchoProbeReview } from './echo-probe-review'; import { EchoCompletionReview } from './echo-completion-review'; import { SyncAlignmentReview } from './sync-alignment-review'; import { SystemNonstartReview } from './system-nonstart-review'; const unknown = 'Nicht gemeldet'; const number = new Intl.NumberFormat('de-DE', { maximumFractionDigits: 1 }); const date = new Intl.DateTimeFormat('de-DE', { dateStyle: 'medium', timeStyle: 'short' }); function label(value: unknown) { return typeof value === 'string' && value.trim() ? value : unknown; } function time(value: unknown) { const t = typeof value === 'string' ? Date.parse(value) : NaN; return Number.isFinite(t) ? date.format(t) : unknown; } function gib(v: unknown) { return typeof v === 'number' && Number.isFinite(v) && v >= 0 ? number.format(v / 2 ** 30) : null; } function capacity(free: unknown, total: unknown) { const f = gib(free), t = gib(total); return f === null && t === null ? unknown : `${f ?? '–'} / ${t ?? '–'} GiB`; } function cpuUsage(value: unknown) { return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 100 ? `${number.format(value)} %` : unknown; } function measuredAt(value: unknown) { const observed = time(value); return observed === unknown ? undefined : `Gemessen am ${observed}`; } function cpu(d: RecordValue) { const model = label(d.cpu_model), count = d.cpu_logical_count; const threads = typeof count === 'number' && count > 0 ? `${count} log. CPU${count === 1 ? '' : 's'}` : ''; return { primary: model === unknown ? threads || unknown : model, secondary: model === unknown ? '' : threads }; } const states: Record = { online: 'Online', offline: 'Offline', never_seen: 'Ohne Erstkontakt', revoked: 'Widerrufen', archived: 'Archiviert', replaced: 'Ersetzt', unverified: 'Identität unbestätigt' }; function Presence({ d }: { d: RecordValue }) { const state = typeof d.lifecycle === 'string' && d.lifecycle !== 'current' ? d.lifecycle : String(d.status); return ( {states[state] ?? 'Unbekannt'} ); } function Capacity({ free, total }: { free: unknown; total: unknown }) { return ( <> {capacity(free, total)} {typeof free === 'number' && typeof total === 'number' && Number.isFinite(total) && free >= 0 && free <= total && total > 0 && ( )} ); } type Target = { customer: string; ids: string[] }; type Props = { detailPath: string; auth: Session; customers: Tenant[]; filter: string; onFilter: (id: string) => void; selection: Target; onSelection: (s: Target) => void; onCreateOrder: () => void; onEnroll: () => void; onOperation: (customer: string, id: string, jobId: string) => void; }; function devicePath(customer: string, asset: string) { return tenantPath(customer, '/devices/' + encodeURIComponent(asset)); } function reportedScriptProfiles(device: RecordValue) { const os = devicePlatform(device); if (!os || !Array.isArray(device.capabilities)) return 'Nicht gemeldet'; const caps = new Set(device.capabilities); if (!caps.has('run_script')) return 'Nicht gemeldet'; const windows = os === 'windows'; const identity = windows ? 'system' : 'root'; const service = windows ? 'PowerShell als Dienstkonto' : 'Shell als Dienstkonto'; if (!caps.has(os + '.base/1') || caps.has(windows ? 'linux.base/1' : 'windows.base/1')) return 'Nicht gemeldet'; if (windows && !['rmm.sync.v1', 'script.powershell/1', 'script.powershell.process_remote_signed/1'].every(cap => caps.has(cap))) return 'Nicht gemeldet'; const admin = ['rmm.sync.v1', 'script.full_maintenance/1', 'helper.' + identity + '.v1', identity + ':run_script'] .every(capability => caps.has(capability)); return admin ? service + ' und als Administrator (' + (windows ? 'SYSTEM' : 'root') + ')' : service; } function DeviceDetail({ customer, asset, agent, auth, customers, back, openOperation, changed }: { customer: string; asset: string; agent: string; auth: Session; customers: Tenant[]; back: () => void; openOperation: (id: string, jobId: string) => void; changed: (notice?: string) => void; }) { const path = devicePath(customer, asset); const detail = useResource( async (signal) => record(await request(path + '?agent_id=' + encodeURIComponent(agent), { signal })), [customer, asset, agent], true ); const membership = useResource( async (signal) => session(await request('/auth/session', { signal, tenantId: customer })), [customer, auth.principal.id] ); const [busy, setBusy] = useState(false), [error, setError] = useState(null); const [confirmDelete, setConfirmDelete] = useState(false); const [managing, setManaging] = useState(false); const d = detail.data; const scoped = membership.data; const volumes = Array.isArray(d?.volumes) ? d.volumes.map((v) => record(v)) : []; const jobs = Array.isArray(d?.recent_jobs) ? d.recent_jobs.map((v) => record(v)) : null; const facts = d && [ ['Kunde', label(d.customer_name)], ['Type', label(d.device_type)], ['Betriebssystem', label(d.os)], ...systemDetails(d, time), ['RAM frei / gesamt', capacity(d.ram_available_bytes, d.ram_total_bytes)], ['CPU', [cpu(d).primary, cpu(d).secondary].filter(Boolean).join(' · ')], ['CPU-Auslastung', [cpuUsage(d.cpu_usage_percent), measuredAt(d.cpu_usage_observed_at)].filter(Boolean).join(' · ')], ['Speicher frei / gesamt', capacity(d.disk_free_bytes, d.disk_total_bytes)], ['Letzter Kontakt', time(d.last_contact_at)], ['Inventar erhoben', time(d.observed_at)], ['Agentversion', label(d.agent_version)], ['Vom Agenten gemeldete Skriptausführung', reportedScriptProfiles(d)] ]; return (
{!d && !detail.error &&

Inventar wird geladen …

} {d && ( <>

{label(d.hostname)}

Geräteinformationen

{facts?.map(([k, v]) => (
{k}
{v}
))}
{volumes.length > 0 && (

Laufwerke

{volumes.map((v, i) => ( ))}
Laufwerk Speicher frei / gesamt
{label(v.name)} {capacity(v.free_bytes, v.total_bytes)}
)} {jobs && (

Letzte Aufträge

{jobs.length === 0 ? (

Keine Aufträge für dieses Gerät.

) : ( )}
)}
Technische Daten
{pretty(d)}
{scoped && allowed(scoped, 'devices:revoke') && d.tenant_id === customer && d.asset_id === asset && d.agent_id === agent && (
setManaging(e.currentTarget.open)}> Gerät verwalten {d.device_type === 'virtual' && d.lifecycle === 'current' && } {['archived', 'current'].includes(String(d.lifecycle)) && ( )} {d.lifecycle !== 'revoked' && (

Die Kopplung von {label(d.hostname)} bei {label(d.customer_name)} {' '}wird mit ihrem Inventar und ihren Geräteergebnissen dauerhaft gelöscht. Andere Installationen bleiben erhalten.

Kopplungs-ID {agent}

) : ( ))} )} {scoped?.principal.simulated && customer === recoveryTenant && asset === recoveryAsset && allowed(scoped, 'inventory:read') && (
Entwicklungsabnahmen
)} )} ); } export function Devices({ detailPath, auth, customers, filter, onFilter, selection, onSelection, onEnroll, onCreateOrder, onOperation }: Props) { const [search, setSearch] = useState(''), [query, setQuery] = useState(''), [status, setStatus] = useState(''), [history, setHistory] = useState(false); const [deletionNotice, setDeletionNotice] = useState(''); const [trail, setTrail] = useState<{ filter: string; routes: string[] }>({ filter, routes: [] }); const routes = trail.filter === filter ? trail.routes : []; function setRoutes(next: string[] | ((old: string[]) => string[])) { setTrail(old => ({ filter, routes: typeof next === 'function' ? next(old.filter === filter ? old.routes : []) : next })); } const [customerId, assetId, agentId] = detailPath.split('/'); const target = customerId && assetId && agentId ? { customer: customerId, asset: assetId, agent: agentId } : null; const back = () => { window.location.hash = 'geraete'; }; const cursor = routes[routes.length - 1]; useEffect(() => { const timer = setTimeout(() => { setQuery(search.trim()); setRoutes([]); }, 200); return () => clearTimeout(timer); }, [search]); useEffect(() => setTrail({ filter, routes: [] }), [filter]); const list = useResource( async (signal) => { if (target) return null; const params = new URLSearchParams({ view: history ? 'history' : 'current', limit: '40' }); if (query) params.set('q', query); if (status && !history) params.set('status', status); if (cursor) params.set('cursor', cursor); const path = filter ? tenantPath(filter, '/devices') : '/api/v1/devices'; return page(await request(path + '?' + params, { signal })); }, [filter, query, history, status, cursor, detailPath], true ); function setView(historic: boolean) { setRoutes([]); setHistory(historic); onSelection({ customer: '', ids: [] }); } function select(d: RecordValue, checked: boolean) { const asset = objectId(d, 'asset'), customer = objectId(d, 'tenant'); if (checked && selection.ids.length && customer !== selection.customer) return; const ids = checked ? [...selection.ids, asset] : selection.ids.filter((id) => id !== asset); onSelection({ customer: ids.length ? customer : '', ids }); } if (target) return ( onOperation(target.customer, id, jobId)} changed={(notice) => { setDeletionNotice(notice ?? ''); back(); setRoutes([]); onSelection({ customer: '', ids: [] }); list.reload(); }} /> ); return ( <>

Geräte

{allowed(auth, 'devices:enroll') && ( )}
{deletionNotice &&

{deletionNotice}

}
{!history && ( )}
{history && (

Ausgemusterte Geräte und Registrierungen ohne bestätigte Identität.

)} {!list.data && !list.error &&

Geräte werden geladen …

} {list.data && ( <>
{!history && ( )} {['Hostname', 'Type', 'OS', 'Status', 'Speicher frei / gesamt', 'RAM frei / gesamt', 'CPU', 'Kunde'].map( (h) => ( ) )} {list.data.items.map((d) => { const asset = objectId(d, 'asset'), agent = objectId(d, 'agent'), customer = objectId(d, 'tenant'), model = cpu(d); const show = () => { setDeletionNotice(''); window.location.hash = ['geraete', customer, asset, agent] .map(encodeURIComponent) .join('/'); }; const another = selection.ids.length > 0 && selection.customer !== customer; return ( {!history && ( )} ); })}
Ziel auswählen {h}
e.stopPropagation()}> select(d, e.target.checked)} /> {label(d.device_type)} {label(d.os)} {d.status === 'offline' && d.lifecycle === 'current' && ( Zuletzt {time(d.last_contact_at)} )} {model.primary} {model.secondary && {model.secondary}} Auslastung {cpuUsage(d.cpu_usage_percent)} {label(d.customer_name)}
{!list.data.items.length && (

{query || filter || status ? 'Keine passenden Geräte' : 'Keine Geräte in dieser Ansicht'}

{(query || filter || status) && ( )}
)}
{list.data.items.length} {list.data.items.length === 1 ? 'Gerät' : 'Geräte'} {cursor || list.data.next_cursor ? ' auf dieser Seite' : ''} · Stand{' '} {time(list.data.as_of)} {(cursor || list.data.next_cursor) && (
)}
)}
{!!selection.ids.length && (
{selection.ids.length} {selection.ids.length === 1 ? 'Gerät' : 'Geräte'} ausgewählt {customers.find((c) => c.tenant_id === selection.customer)?.name}
)} ); }