2026_10_08_ki

This commit is contained in:
marco committed 2026-10-09 08:27:07 +02:00
1 parent 05f4390392
commit 13bbd26ce5
16 files changed
+833 -147

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
"use client";
import { useEffect, useState } from "react";
import { api_ios } from "@/actions/rk2/api-ios";
import { Button } from "@/components/ui/button";
import { ioExcelRowsToIos } from "@/lib/ioExcelToIos";
import type { IoCreate, IoResponse } from "@/types/anlagen/ios";
import type { IoExcelRow } from "@/types/anlagen/signals";
interface Props {
rows: IoExcelRow[];
anlageId: string;
isSaving: boolean;
}
const fields = ['functionText', 'seite', 'seiteName', 'spsKarte'] as const;
const labels = { functionText: 'Funktionstext', seite: 'Seite', seiteName: 'Seitenname', spsKarte: 'SPS-Karte' };
interface ComparedRow {
excel?: IoCreate & { spsKarte?: string };
io?: IoResponse & { spsKarte?: string };
}
function addressKey(io: IoCreate) {
return JSON.stringify([io.adrType, io.adrByte, io.adrBit ?? null]);
}
function card(io: IoResponse): string | undefined {
if (!io.excelData) return undefined;
try {
const data: unknown = JSON.parse(io.excelData);
if (typeof data === 'object' && data !== null && 'spsKarte' in data) {
return data.spsKarte == null ? undefined : String(data.spsKarte);
}
} catch { /* Ältere IOs können unstrukturierte Excel-Daten enthalten. */ }
return undefined;
}
export default function IoExcelCompare({ rows, anlageId, isSaving }: Props) {
const [ios, setIos] = useState<IoResponse[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string>();
const [version, setVersion] = useState(0);
useEffect(() => {
if (isSaving) return;
let active = true;
setLoading(true);
setError(undefined);
api_ios().then((data) => {
if (active) setIos(data.filter((io) => io.anlageId === anlageId));
}).catch(() => {
if (active) setError('IO-Daten konnten nicht geladen werden. Bitte erneut versuchen.');
}).finally(() => {
if (active) setLoading(false);
});
return () => { active = false; };
}, [anlageId, isSaving, version]);
let excel: IoCreate[] = [];
let conversionError: string | undefined;
try {
excel = ioExcelRowsToIos(rows);
} catch (error: unknown) {
conversionError = error instanceof Error ? error.message : 'Excel-Daten sind ungültig.';
}
const excelKeys = new Set(excel.map(addressKey));
const ioMap = new Map<string, IoResponse[]>();
for (const io of ios) {
const key = addressKey(io);
ioMap.set(key, [...(ioMap.get(key) ?? []), io]);
}
const compared = excel.flatMap<ComparedRow>((row, index) => {
const matches = ioMap.get(addressKey(row));
const excelValues = { ...row, spsKarte: rows[index].spsKarte };
return matches?.length
? matches.map((io) => ({ excel: excelValues, io: { ...io, spsKarte: card(io) } }))
: [{ excel: excelValues, io: undefined }];
});
const allRows = [
...compared,
...ios.filter((io) => !excelKeys.has(addressKey(io))).map((io) => ({ excel: undefined, io: { ...io, spsKarte: card(io) } })),
];
return <section className="mt-6">
<div className="flex items-center gap-4">
<h2 className="font-semibold">Excel / IO Vergleich</h2>
<Button type="button" onClick={() => setVersion((value) => value + 1)} disabled={loading || isSaving}>Vergleich aktualisieren</Button>
</div>
<div className="my-3 flex flex-wrap gap-4 text-gray-900">
<span className="bg-red-100 px-2">Rot: Unterschiede</span>
<span className="bg-blue-100 px-2">Blau: In Excel nicht vorhanden</span>
<span className="bg-yellow-100 px-2">Gelb: In IOs nicht vorhanden</span>
</div>
{loading && <p role="status">IO-Daten werden geladen…</p>}
{(error || conversionError) && <p role="alert">{error ?? conversionError}</p>}
{!loading && !error && !conversionError && <div className="overflow-x-auto">
<table className="w-full border-collapse text-sm">
<thead><tr>
<th className="border p-2 text-left">Status</th>
<th className="border p-2 text-left">Typ</th>
<th className="border p-2 text-left">Adresse</th>
{fields.map((field) => <th key={field} className="border p-2 text-left">{labels[field]}<div className="font-normal">Excel / IO</div></th>)}
</tr></thead>
<tbody>{allRows.map((pair, index) => {
const different = fields.some((field) => (pair.excel?.[field] ?? '') !== (pair.io?.[field] ?? ''));
const status = !pair.excel ? 'In Excel nicht vorhanden' : !pair.io ? 'In IOs nicht vorhanden' : different ? 'Unterschiede' : 'Gleich';
const color = !pair.excel ? 'bg-blue-100 text-gray-900' : !pair.io ? 'bg-yellow-100 text-gray-900' : different ? 'bg-red-50 text-gray-900' : '';
const address = pair.excel ?? pair.io!;
return <tr key={index} className={color}>
<td className="border p-2">{status}</td>
<td className="border p-2">{address.adrType} </td>
<td className="border p-2">{address.adrByte}.{address.adrBit ?? '–'}</td>
{fields.map((field) => <td key={field} className={`border p-2 ${pair.excel && pair.io && (pair.excel[field] ?? '') !== (pair.io[field] ?? '') ? 'bg-red-200 text-gray-900' : ''}`}>
<div>Excel: {pair.excel?.[field] ?? '–'}</div>
<div>IO: {pair.io?.[field] ?? '–'}</div>
</td>)}
</tr>;
})}</tbody>
</table>
{allRows.length === 0 && <p>Keine Datensätze vorhanden.</p>}
</div>}
</section>;
}
+39
View File
@@ -0,0 +1,39 @@
"use client";
import { useState } from "react";
import type { IoExcelData } from "@/types/anlagen/signals";
import IoExcelUpload from "./ioExcelUpload";
import IoExcelSave from "./ioExcelSave";
import IoExcelCompare from "./ioExcelCompare";
export default function IoExcelImport({ anlageId }: { anlageId: string }) {
const [data, setData] = useState<IoExcelData>();
const [isSaving, setIsSaving] = useState(false);
const [uploadVersion, setUploadVersion] = useState(0);
return (
<div>
<fieldset disabled={isSaving}>
<IoExcelUpload onLoadData={(loaded) => {
setData(loaded);
setUploadVersion((version) => version + 1);
}} />
</fieldset>
{data && <div className="mt-4">
<IoExcelSave key={uploadVersion} rows={data.data} onSavingChange={setIsSaving} />
<IoExcelCompare rows={data.data} anlageId={anlageId} isSaving={isSaving} />
{data.data.length === 0 && <p>Keine Datensätze gefunden.</p>}
{data.data.map((row, index) => <div key={index} className="flex gap-4">
<div className="w-200">{row.functionText}</div>
<div>{row.adrType}</div>
<div>{row.adrByte}</div>
<div>{row.adrBit}</div>
<div>{row.seite}</div>
<div>{row.seiteName}</div>
<div>{row.spsKarte}</div>
</div>)}
</div>}
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
"use client";
import { useState } from "react";
import { api_ios_bulkCreate, api_ios_bulkUpdate } from "@/actions/rk2/api-ios";
import { Button } from "@/components/ui/button";
import { ioExcelRowsToIos } from "@/lib/ioExcelToIos";
import type { IoExcelRow } from "@/types/anlagen/signals";
interface Props {
rows: IoExcelRow[];
onSavingChange: (saving: boolean) => void;
}
export default function IoExcelSave({ rows, onSavingChange }: Props) {
const [isSaving, setIsSaving] = useState(false);
const [savedCount, setSavedCount] = useState<number>();
const [errors, setErrors] = useState<string[]>([]);
const [updateMessage, setUpdateMessage] = useState<string>();
const importIos = async () => {
if (isSaving || savedCount !== undefined || rows.length === 0) return;
setIsSaving(true);
onSavingChange(true);
setErrors([]);
try {
const result = await api_ios_bulkCreate(ioExcelRowsToIos(rows));
if (!result.success) {
setErrors(result.errors);
return;
}
setSavedCount(result.data.length);
} catch (error: unknown) {
setErrors([error instanceof Error ? error.message : 'IO-Import fehlgeschlagen.']);
} finally {
setIsSaving(false);
onSavingChange(false);
}
};
const updateIos = async () => {
if (isSaving || rows.length === 0) return;
setIsSaving(true);
onSavingChange(true);
setErrors([]);
setUpdateMessage(undefined);
try {
const result = await api_ios_bulkUpdate(ioExcelRowsToIos(rows));
if (!result.success) {
setErrors(result.errors);
return;
}
const { modified, unchanged, missing, duplicates } = result.data;
setUpdateMessage(`${modified} IOs aktualisiert, ${unchanged} unverändert, ${missing} nicht vorhanden, ${duplicates} doppelte Importzeilen übersprungen.`);
} catch (error: unknown) {
setErrors([error instanceof Error ? error.message : 'IO-Aktualisierung fehlgeschlagen.']);
} finally {
setIsSaving(false);
onSavingChange(false);
}
};
return <div className="my-4">
<Button type="button" onClick={importIos} disabled={isSaving || savedCount !== undefined || rows.length === 0}>
{isSaving ? 'IOs werden verarbeitet…' : 'Neue IOs speichern'}
</Button>
<Button className="ml-2" type="button" onClick={updateIos} disabled={isSaving || rows.length === 0}>
Vorhandene IOs aktualisieren
</Button>
{savedCount !== undefined && <p role="status">{savedCount} IO-Datensätze gespeichert, {rows.length - savedCount} vorhandene oder doppelte Datensätze übersprungen.</p>}
{updateMessage && <p role="status">{updateMessage}</p>}
{errors.length > 0 && <div role="alert">{errors.map((error, index) => <p key={index}>{error}</p>)}</div>}
</div>;
}
+63
View File
@@ -0,0 +1,63 @@
"use client";
import { api_signals_excel_upload } from "@/actions/rk2/api-signals";
import { IoExcelData } from "@/types/anlagen/signals";
import { useState } from "react";
interface Props {
onLoadData: (excelData: IoExcelData) => void
}
export default function IoExcelUpload({ onLoadData }: Props) {
const [file, setFile] = useState<File | null>(null);
const [error, setError] = useState<string>();
const [isUploading, setIsUploading] = useState(false);
const uploadExcel = async () => {
if (!file || isUploading) return;
setError(undefined);
setIsUploading(true);
const formData = new FormData();
formData.append("file", file);
try {
const response = await api_signals_excel_upload(formData)
if (!response.success) {
setError(Array.isArray(response.errors) ? response.errors.join(', ') : String(response.errors));
return;
}
onLoadData(response.data);
} catch {
setError('Upload fehlgeschlagen. Bitte versuche es erneut.');
} finally {
setIsUploading(false);
}
};
return (
<div>
<input
type="file"
accept=".xlsx,.xls"
onChange={(e) =>
setFile(e.target.files?.[0] ?? null)
}
/>
<button type="button" onClick={uploadExcel} disabled={!file || isUploading}>
{isUploading ? 'Excel wird geladen…' : 'Excel hochladen'}
</button>
{error && <p role="alert">{error}</p>}
</div>
);
}
/*
{data && JSON.stringify(data)}
*/
+23
View File
@@ -0,0 +1,23 @@
"use client";
interface Props {
functionText: string;
adrByte: string;
onFunctionTextChange: (value: string) => void;
onAdrByteChange: (value: string) => void;
}
export default function IoFilter({ functionText, adrByte, onFunctionTextChange, onAdrByteChange }: Props) {
return <div className="mb-3 grid gap-2">
<p className="text-sm">Treffer im Funktionstext oder in der Byteadresse.</p>
<p className="text-sm">Mehrere Textbegriffe mit Leerzeichen trennen: Alle Begriffe müssen vorkommen.</p>
<label>Funktionstext
<input type="search" className="mt-1 w-full rounded border p-2" value={functionText}
onChange={(event) => onFunctionTextChange(event.target.value)} placeholder="Funktionstext suchen" />
</label>
<label>Byteadresse
<input type="number" min={0} step={1} className="mt-1 w-full rounded border p-2" value={adrByte}
onChange={(event) => onAdrByteChange(event.target.value)} placeholder="Alle Byteadressen" />
</label>
</div>;
}
@@ -1,48 +0,0 @@
"use client";
import { api_signals_excel_upload } from "@/actions/rk2/api-signals";
import { useState } from "react";
interface Props{
onLoadData?:any
}
export default function SignalExcelUpload() {
const [file, setFile] = useState<File | null>(null);
const [data, setData] = useState<any>();
const uploadExcel = async () => {
if (!file) return;
const formData = new FormData();
formData.append("file", file);
const response = await api_signals_excel_upload(formData)
if (!response.success) {
throw new Error("Upload fehlgeschlagen");
}
const result = await response.data;
setData(result)
console.log(result);
};
return (
<div>
<input
type="file"
accept=".xlsx,.xls"
onChange={(e) =>
setFile(e.target.files?.[0] ?? null)
}
/>
<button onClick={uploadExcel}>
Excel hochladen
</button>
{data && <div>{JSON.stringify(data,null,2)}</div>}
</div>
);
}
@@ -0,0 +1,276 @@
"use client";
import { useEffect, useState } from "react";
import { api_signals_assignIos, api_signals } from "@/actions/rk2/api-signals";
import { Button } from "@/components/ui/button";
import IoFilter from "@/components/rk2/ios/ioFilter";
import type { GroupResponse } from "@/types/anlagen/groups";
import type { UnitResponse } from "@/types/anlagen/units";
import type { SignalResponse } from "@/types/anlagen/signals";
import type { IoResponse } from "@/types/anlagen/ios";
interface Props {
groups: GroupResponse[];
units: UnitResponse[];
signals: SignalResponse[];
ios: IoResponse[];
anlageId: string;
}
function ioLabel(io: IoResponse) {
return `${io.adrType} ${io.adrByte}${io.adrBit == null ? '' : `.${io.adrBit}`} – ${io.functionText ?? ''}`;
}
function groupPath(id: string | undefined, groups: GroupResponse[]): string {
if (!id) return 'Ohne Gruppe';
const parts: string[] = [];
const visited = new Set<string>();
let group = groups.find((item) => item.id === id);
while (group && !visited.has(group.id)) {
visited.add(group.id);
parts.unshift(`${group.nr} ${group.name}`.trim());
group = groups.find((item) => item.id === group?.parentId);
}
return parts.join(' / ') || 'Unbekannte Gruppe';
}
export default function SignalIoAssignment({ groups, units, signals: initialSignals, ios, anlageId }: Props) {
const [signals, setSignals] = useState(initialSignals);
const [pending, setPending] = useState<Record<string, string | null>>({});
const effectiveSignals = signals.map((item) => Object.hasOwn(pending, item.id) ? { ...item, ioId: pending[item.id] ?? undefined } : item);
const pendingCount = Object.keys(pending).length;
useEffect(() => {
if (!pendingCount) return;
const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ''; };
window.addEventListener('beforeunload', warn);
return () => window.removeEventListener('beforeunload', warn);
}, [pendingCount]);
const [unitId, setUnitId] = useState('');
const [signalId, setSignalId] = useState('');
useEffect(() => {
document.getElementById(`assignment-signal-${signalId}`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
}, [signalId]);
const [ioId, setIoId] = useState('');
const [functionText, setFunctionText] = useState('');
const [adrByte, setAdrByte] = useState('');
const [hideAssigned, setHideAssigned] = useState(false);
const [hideUsedIos, setHideUsedIos] = useState(false);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState('');
const [error, setError] = useState('');
const unit = units.find((item) => item.id === unitId);
const signal = effectiveSignals.find((item) => item.id === signalId);
const selectedIo = ios.find((item) => item.id === ioId);
const owners = new Map<string, SignalResponse[]>();
for (const item of effectiveSignals) if (item.ioId) owners.set(item.ioId, [...(owners.get(item.ioId) ?? []), item]);
const occupied = (owners.get(ioId) ?? []).some((item) => item.id !== signalId);
const pendingIoIds = new Set(Object.values(pending).filter((id): id is string => id !== null));
const textFilter = functionText.trim().toLocaleLowerCase('de');
const textTerms = textFilter.split(/\s+/).filter(Boolean);
const byteFilter = adrByte.trim();
const visibleIos = ios.filter((io) => io.anlageId === anlageId && !pendingIoIds.has(io.id)
&& (!hideUsedIos || !owners.has(io.id))
&& ((!textFilter && !byteFilter)
|| (textTerms.length > 0 && textTerms.every((term) => (io.functionText ?? '').toLocaleLowerCase('de').includes(term)))
|| (byteFilter !== '' && io.adrByte === Number(byteFilter))))
.sort((a, b) => a.adrByte - b.adrByte || (a.adrBit ?? -1) - (b.adrBit ?? -1) || a.adrType.localeCompare(b.adrType));
const unitGroups = new Map<string, UnitResponse[]>();
for (const item of [...units].sort((a, b) => a.name.localeCompare(b.name, 'de', { numeric: true }))) {
const key = item.groupId ?? '';
unitGroups.set(key, [...(unitGroups.get(key) ?? []), item]);
}
const sortedGroups = [...unitGroups.entries()].sort(([a], [b]) =>
groupPath(a, groups).localeCompare(groupPath(b, groups), 'de', { numeric: true }));
const orderedUnits = sortedGroups.flatMap(([, items]) => items);
const unitSignals = (target: UnitResponse | undefined) => target?.components.flatMap((component) =>
effectiveSignals.filter((item) => item.anlageId === anlageId && item.componentId === component.id && !Object.hasOwn(pending, item.id) && (!hideAssigned || !item.ioId))) ?? [];
const chooseUnit = (target: UnitResponse) => {
setUnitId(target.id);
setSignalId(unitSignals(target).find((item) => !item.ioId)?.id ?? unitSignals(target)[0]?.id ?? '');
setIoId('');
};
const stage = (targetIoId: string | null) => {
if (!signal || busy) return;
if (targetIoId && (owners.get(targetIoId) ?? []).some((owner) => owner.id !== signal.id)) return;
setPending((items) => {
const updated = { ...items };
const original = signals.find((item) => item.id === signal.id)?.ioId ?? null;
if (original === targetIoId) delete updated[signal.id];
else updated[signal.id] = targetIoId;
return updated;
});
setMessage(`Zuordnung für ${signal.name} vorgemerkt.`);
setError('');
setIoId('');
if (targetIoId !== null) {
const items = unitSignals(unit);
const index = items.findIndex((item) => item.id === signal.id);
const remaining = [...items.slice(index + 1), ...items.slice(0, index)]
.find((item) => !item.ioId);
setSignalId(remaining?.id ?? '');
}
};
const removePending = (id: string) => {
if (busy) return;
const originalIo = signals.find((item) => item.id === id)?.ioId;
if (originalIo && (owners.get(originalIo) ?? []).some((item) => item.id !== id)) {
setError('Der ursprüngliche IO ist inzwischen vorgemerkt. Nimm zuerst diese andere Zuordnung zurück.');
return;
}
setPending((items) => { const updated = { ...items }; delete updated[id]; return updated; });
setError('');
setMessage('Vormerkung zurückgenommen.');
};
const saveAll = async () => {
if (!pendingCount || busy) return;
setBusy(true);
setError('');
setMessage('');
try {
const result = await api_signals_assignIos(Object.entries(pending).map(([id, target]) => ({
signalId: id, ioId: target, previousIoId: signals.find((item) => item.id === id)?.ioId ?? null,
})));
if (!result.success) { setError(result.errors.join(', ')); return; }
const saved = new Map(result.data.map((item) => [item.id, item]));
setSignals((items) => items.map((item) => saved.get(item.id) ?? item));
setPending({});
setMessage(`${result.data.length} Zuordnungen gespeichert.`);
try { setSignals(await api_signals()); }
catch { setError('Gespeichert; aktuelle Belegungen konnten nicht nachgeladen werden.'); }
} catch { setError('Speichern fehlgeschlagen. Vormerkungen bleiben erhalten.'); }
finally { setBusy(false); }
};
return <div className="mt-4">
<div className="sticky top-0 z-10 mb-4 rounded border bg-white p-3 text-gray-900">
<div className="mb-2 font-semibold">{pendingCount} Zuordnungen ausstehend</div>
<div className="mb-2">Signal: <strong>{signal ? `${unit?.name ?? ''} / ${signal.name}` : 'Bitte auswählen'}</strong></div>
<div className="mb-3">IO: <strong>{selectedIo ? ioLabel(selectedIo) : 'Bitte auswählen'}</strong></div>
<div className="flex flex-wrap gap-2">
<Button type="button" disabled={busy || !pendingCount} onClick={saveAll}>
{busy ? 'Wird gespeichert…' : 'Alle speichern'}
</Button>
<Button type="button" variant="secondary" disabled={busy || !signal?.ioId} onClick={() => stage(null)}>Zuordnung entfernen</Button>
<Button type="button" variant="secondary" disabled={busy || !signal || !Object.hasOwn(pending, signal.id)} onClick={() => {
const originalIo = signals.find((item) => item.id === signalId)?.ioId;
if (originalIo && (owners.get(originalIo) ?? []).some((item) => item.id !== signalId)) {
setError('Der ursprüngliche IO ist inzwischen vorgemerkt. Nimm zuerst diese andere Zuordnung zurück.');
return;
}
setPending((items) => { const updated = { ...items }; delete updated[signalId]; return updated; });
}}>Änderung zurücknehmen</Button>
<Button type="button" variant="secondary" disabled={busy || !orderedUnits.length || orderedUnits.findIndex((item) => item.id === unitId) === orderedUnits.length - 1} onClick={() => {
const target = orderedUnits[orderedUnits.findIndex((item) => item.id === unitId) + 1];
if (target) chooseUnit(target);
}}>Nächste Unit</Button>
</div>
{occupied && <p className="mt-2">Dieser IO ist bereits einem anderen Signal zugeordnet.</p>}
{error && <p role="alert" className="mt-2">{error}</p>}
{message && <p role="status" className="mt-2">{message}</p>}
</div>
<div className="grid gap-4 lg:grid-cols-2 2xl:grid-cols-[minmax(12rem,0.8fr)_minmax(16rem,1fr)_minmax(18rem,1.2fr)_minmax(18rem,1.2fr)]">
<section className="min-w-0 rounded border p-3">
<h2 className="mb-3 font-semibold">Units nach Gruppe</h2>
<div className="max-h-[65vh] overflow-y-auto">
{sortedGroups.map(([id, items]) => <div key={id} className="mb-4">
<h3 className="mb-2 text-sm font-semibold">{groupPath(id, groups)}</h3>
{items.map((item) => <button type="button" key={item.id} disabled={busy} aria-pressed={unitId === item.id}
className={`mb-1 block w-full rounded border p-2 text-left ${unitId === item.id ? 'border-blue-500 bg-blue-100 text-gray-900' : 'hover:bg-gray-100 hover:text-gray-900'}`}
onClick={() => { chooseUnit(item); setMessage(''); setError(''); }}>
{item.name} {item.bmk ?? ''}
</button>)}
</div>)}
{units.length === 0 && <p>Keine Units vorhanden.</p>}
</div>
</section>
<section className="min-w-0 rounded border p-3">
<h2 className="mb-3 font-semibold">Signale {unit && `– ${unit.name}`}</h2>
<label className="mb-3 flex items-center gap-2">
<input type="checkbox" checked={hideAssigned} disabled={busy} onChange={(event) => {
setHideAssigned(event.target.checked);
if (event.target.checked && signal?.ioId) { setSignalId(''); setIoId(''); }
}} />
Zugeordnete Signale ausblenden
</label>
{!unit && <p>Unit auswählen, dann ein IO anklicken. Das nächste freie Signal wird automatisch ausgewählt.</p>}
<div className="max-h-[65vh] overflow-y-auto" onKeyDown={(event) => {
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
event.preventDefault();
const items = unitSignals(unit);
const index = items.findIndex((item) => item.id === signalId);
const target = items[Math.max(0, Math.min(items.length - 1, index + (event.key === 'ArrowDown' ? 1 : -1)))];
if (target) { setSignalId(target.id); document.getElementById(`assignment-signal-${target.id}`)?.focus(); }
}}>
{unit?.components.map((component) => {
const items = effectiveSignals.filter((item) => item.anlageId === anlageId && item.componentId === component.id && !Object.hasOwn(pending, item.id) && (!hideAssigned || !item.ioId));
return <div key={component.id} className="mb-4">
<h3 className="mb-2 text-sm font-semibold">{component.name}</h3>
{items.map((item) => {
const current = ios.find((io) => io.id === item.ioId);
return <button id={`assignment-signal-${item.id}`} key={item.id} type="button" disabled={busy} aria-pressed={signalId === item.id}
className={`mb-2 block w-full rounded border p-2 text-left ${item.ioId ? 'border-green-400 bg-green-100 text-green-950' : 'hover:bg-gray-100 hover:text-gray-900'} ${signalId === item.id ? 'ring-2 ring-blue-500' : ''}`}
onClick={() => { setSignalId(item.id); setIoId(''); setMessage(''); setError(''); }}>
<div className="font-medium">{item.ioId && <span className="mr-2" aria-label="Zugeordnet">✓</span>}{item.name} ({item.type})</div>
<div className="text-sm">{item.description}</div>
<div className="mt-1 text-sm">{current ? ioLabel(current) : item.ioId ? 'Zugeordneter IO nicht verfügbar' : 'Ohne IO'}</div>
</button>;
})}
{items.length === 0 && <p>Keine Signale.</p>}
</div>;
})}
{unit?.components.length === 0 && <p>Keine Komponenten vorhanden.</p>}
</div>
</section>
<section className="min-w-0 rounded border p-3">
<h2 className="mb-3 font-semibold">IOs der Anlage ({visibleIos.length})</h2>
<label className="mb-3 flex items-center gap-2">
<input type="checkbox" checked={hideUsedIos} disabled={busy} onChange={(event) => {
setHideUsedIos(event.target.checked);
if (event.target.checked && owners.has(ioId)) setIoId('');
}} />
Benutzte IOs ausblenden
</label>
<IoFilter functionText={functionText} adrByte={adrByte} onFunctionTextChange={setFunctionText} onAdrByteChange={setAdrByte} />
<div className="max-h-[55vh] overflow-y-auto">
{visibleIos.map((io) => {
const ownerList = owners.get(io.id) ?? [];
const taken = ownerList.some((item) => item.id !== signalId);
return <button key={io.id} type="button" disabled={busy || taken} aria-pressed={ioId === io.id}
className={`mb-2 block w-full rounded border p-2 text-left disabled:opacity-50 ${ioId === io.id ? 'border-blue-500 bg-blue-100 text-gray-900' : 'hover:bg-gray-100 hover:text-gray-900'}`}
onClick={() => { if (signal) stage(io.id); else { setIoId(io.id); setMessage('Bitte zuerst ein Signal auswählen.'); } }}>
<div className="font-medium">{io.adrType} {io.adrByte}{io.adrBit == null ? '' : `.${io.adrBit}`}</div>
<div>{io.functionText || 'Ohne Funktionstext'}</div>
<div className="text-sm">{ownerList.length ? `Belegt: ${ownerList.map((item) => item.name).join(', ')}` : 'Frei'}</div>
</button>;
})}
{visibleIos.length === 0 && <p>Keine IOs passend zum Filter.</p>}
</div>
</section>
<section className="min-w-0 rounded border bg-white p-3 text-gray-900">
<h2 className="mb-3 font-semibold">Vormerkungen ({pendingCount})</h2>
{pendingCount > 0 && <div className="max-h-[65vh] overflow-y-auto">
{Object.entries(pending).map(([id, targetIoId]) => {
const item = signals.find((signal) => signal.id === id);
const targetIo = ios.find((io) => io.id === targetIoId);
const targetUnit = units.find((unit) => unit.components.some((component) => component.id === item?.componentId));
const component = targetUnit?.components.find((component) => component.id === item?.componentId);
return <div key={id} className="mb-2 flex flex-wrap items-center justify-between gap-2 rounded border bg-amber-50 p-2">
<div>
<div className="text-sm">{targetUnit?.name} / {component?.name}</div>
<div><strong>{item?.name ?? id}</strong> → {targetIoId === null ? 'Zuordnung entfernen' : targetIo ? ioLabel(targetIo) : targetIoId}</div>
</div>
<Button type="button" variant="secondary" size="sm" disabled={busy} onClick={() => removePending(id)}>Vormerkung löschen</Button>
</div>;
})}
</div>}
{pendingCount === 0 && <p>Noch keine Zuordnungen vorgemerkt.</p>}
</section>
</div>
</div>;
}