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

+8
View File
@@ -43,6 +43,14 @@ export const componentTypeDefinitions: ComponentTypeDefinition[] = [
required: false,
},
{
key: "rmRtg2",
label: "RueckmeldungRtg2",
type: "boolean",
defaultValue: false,
required: false,
},
{
key: "ms",
label: "Motorschutz",
type: "boolean",
+67 -73
View File
@@ -1,97 +1,91 @@
'use server'
import { Sites } from "@/_config/sites";
import { IoCreate, IoResponse } from "@/types/anlagen/ios";
import type { IoBulkUpdateResult, IoCreate, IoResponse, IoUpdate } from "@/types/anlagen/ios";
import { revalidatePath } from "next/cache";
const url = "http://localhost:3000/rk2/";
const url_ios = url + "ios"
const url_ios = "http://localhost:3000/rk2/ios";
//-----------------------------------------------------------------------------
//--- ios
//-----------------------------------------------------------------------------
function getErrors(data: unknown, status: number): string[] {
if (typeof data === 'object' && data !== null && 'message' in data) {
const message = data.message;
if (typeof message === 'string') return [message];
if (Array.isArray(message) && message.length > 0 && message.every((item) => typeof item === 'string')) {
return message;
}
}
return [`IO-Anfrage fehlgeschlagen (HTTP ${status}).`];
}
async function requestIo<T>(url: string, options: RequestInit): Promise<ActionResult<T>> {
try {
const result = await fetch(url, options);
if (!result.ok) {
const errorData: unknown = await result.json().catch(() => null);
return { success: false, errors: getErrors(errorData, result.status) };
}
const data: T = await result.json();
return { success: true, data };
} catch (error: unknown) {
console.error('IO-Anfrage fehlgeschlagen:', error);
return { success: false, errors: ['Die IO-Anfrage konnte nicht verarbeitet werden. Bitte versuche es erneut.'] };
}
}
export async function api_ios(): Promise<IoResponse[]> {
const result = await fetch(`${url_ios}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
const data = await result.json();
return data;
const result = await requestIo<IoResponse[]>(url_ios, { method: 'GET' });
if (!result.success) throw new Error(result.errors.join('\n'));
return result.data;
}
//-----------------------------------------------------------------------------
//--- io by ID
//-----------------------------------------------------------------------------
export async function api_ios_byId(id: string): Promise<ActionResult<IoResponse>> {
const result = await fetch(`${url_ios}/${id}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
});
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
return { success: true, data:resultData };
return requestIo<IoResponse>(`${url_ios}/${encodeURIComponent(id)}`, { method: 'GET' });
}
//-----------------------------------------------------------------------------
//--- ios CREATE
//-----------------------------------------------------------------------------
export async function api_ios_create(data: IoResponse): Promise<ActionResult<IoResponse>> {
const result = await fetch(`${url_ios}`, {
export async function api_ios_create(data: IoCreate): Promise<ActionResult<IoResponse>> {
const result = await requestIo<IoResponse>(url_ios, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
revalidatePath(Sites.rk2.ios.url + "/")
return { success: true, data:resultData };
});
if (result.success) revalidatePath(Sites.rk2.ios.url);
return result;
}
//-----------------------------------------------------------------------------
//--- ios UPDATE
//-----------------------------------------------------------------------------
export async function api_ios_update(id:string,data: IoCreate): Promise<ActionResult<IoResponse>> {
export async function api_ios_bulkCreate(data: IoCreate[]): Promise<ActionResult<IoResponse[]>> {
const result = await requestIo<IoResponse[]>(`${url_ios}/import`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (result.success) revalidatePath(Sites.rk2.ios.url);
return result;
}
const result = await fetch(`${url_ios}/${id}`, {
export async function api_ios_bulkUpdate(data: IoCreate[], onlyChanged = true): Promise<ActionResult<IoBulkUpdateResult>> {
const result = await requestIo<IoBulkUpdateResult>(`${url_ios}/import?onlyChanged=${onlyChanged}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
const resultData = await result.json();
if (!result.ok) {
return {
success: false,
errors: resultData.message, // kommt aus NestJS
};
}
revalidatePath(Sites.rk2.ios.url)
return { success: true, data:resultData };
});
if (result.success) revalidatePath(Sites.rk2.ios.url);
return result;
}
export async function api_ios_update(id: string, data: IoUpdate): Promise<ActionResult<IoResponse>> {
const result = await requestIo<IoResponse>(`${url_ios}/${encodeURIComponent(id)}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
});
if (result.success) revalidatePath(Sites.rk2.ios.url);
return result;
}
export async function api_ios_delete(id: string): Promise<ActionResult<IoResponse>> {
const result = await requestIo<IoResponse>(`${url_ios}/${encodeURIComponent(id)}`, { method: 'DELETE' });
if (result.success) revalidatePath(Sites.rk2.ios.url);
return result;
}
+38 -2
View File
@@ -1,7 +1,7 @@
'use server'
import { Sites } from "@/_config/sites";
import { SignalCreate, SignalResponse } from "@/types/anlagen/signals";
import { SignalCreate, IoExcelData, SignalResponse } from "@/types/anlagen/signals";
import { revalidatePath } from "next/cache";
const url = "http://localhost:3000/rk2/";
@@ -11,6 +11,42 @@ const url_signals = url + "signals"
//--- Signals
//-----------------------------------------------------------------------------
export async function api_signal_assignIo(id: string, ioId: string | null): Promise<ActionResult<SignalResponse>> {
try {
const response = await fetch(`${url_signals}/${encodeURIComponent(id)}/io`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ioId }),
});
if (!response.ok) {
const data: unknown = await response.json().catch(() => null);
const message = typeof data === 'object' && data !== null && 'message' in data ? data.message : undefined;
return { success: false, errors: [typeof message === 'string' ? message : 'IO-Zuordnung fehlgeschlagen.'] };
}
const data: SignalResponse = await response.json();
revalidatePath('/rk2/signals/assignment');
return { success: true, data };
} catch {
return { success: false, errors: ['IO-Zuordnung konnte nicht gespeichert werden.'] };
}
}
export async function api_signals_assignIos(assignments: { signalId: string; ioId: string | null; previousIoId: string | null }[]): Promise<ActionResult<SignalResponse[]>> {
try {
const response = await fetch(`${url_signals}/io-assignments`, {
method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(assignments),
});
if (!response.ok) {
const data: unknown = await response.json().catch(() => null);
const message = typeof data === 'object' && data !== null && 'message' in data ? data.message : undefined;
return { success: false, errors: [typeof message === 'string' ? message : 'Zuordnungen konnten nicht gespeichert werden.'] };
}
const data: SignalResponse[] = await response.json();
revalidatePath('/rk2/signals/assignment');
return { success: true, data };
} catch { return { success: false, errors: ['Zuordnungen konnten nicht gespeichert werden.'] }; }
}
export async function api_signals(): Promise<SignalResponse[]> {
const result = await fetch(`${url_signals}`, {
@@ -113,7 +149,7 @@ export async function api_signals_update(id:string,data: SignalCreate): Promise<
//-----------------------------------------------------------------------------
//--- Upload EA Excel File
//-----------------------------------------------------------------------------
export async function api_signals_excel_upload(formData:any): Promise<ActionResult<any>> {
export async function api_signals_excel_upload(formData:any): Promise<ActionResult<IoExcelData>> {
const result = await fetch(`${url_signals}/upload`, {
method: 'POST',
@@ -0,0 +1,17 @@
import { api_anlage_getSelected } from "@/actions/rk/api-anlage";
import { api_groups } from "@/actions/rk2/api-groups";
import { api_units } from "@/actions/rk2/api-units";
import { api_signals } from "@/actions/rk2/api-signals";
import { api_ios } from "@/actions/rk2/api-ios";
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
import SignalIoAssignment from "@/components/rk2/signals/signalIoAssignment";
export default async function AssignmentPage() {
const anlage = await api_anlage_getSelected();
const [groups, units, signals, ios] = await Promise.all([api_groups(), api_units(), api_signals(), api_ios()]);
return <div className="m-4">
<Breadcrumbs items={[{ label: 'Signale', href: '/rk2/signals' }, { label: 'IO-Zuordnung' }, { label: `${anlage.anlageNr} ${anlage.name}` }]} />
<SignalIoAssignment groups={groups} units={units.filter((unit) => unit.anlageId === anlage.id)}
signals={signals} ios={ios.filter((io) => io.anlageId === anlage.id)} anlageId={anlage.id} />
</div>;
}
+3 -3
View File
@@ -8,7 +8,7 @@ import Link from "next/link";
import { List, ListItem, ListItemAction } from "@/components/ui/list";
import { Button } from "@/components/ui/button";
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
import SignalExcelUpload from "@/components/rk2/signals/signalExcelUpload";
import IoExcelImport from "@/components/rk2/ios/ioExcelImport";
@@ -23,8 +23,8 @@ export default async function PageImport() {
{/* Main-Nav */}
<Breadcrumbs items={breadcrumb}/>
<div className="flex flex-col m-4 w-170 ">
<SignalExcelUpload />
<div className="flex flex-col m-4 ">
<IoExcelImport anlageId={currentAnlage.id} />
</div>
</>
+3
View File
@@ -24,6 +24,9 @@ export default async function PageSignale() {
<div className="flex flex-col m-4 w-170 ">
<List variant={"default"} size={"lg"} >
<ListItem hover={true}>
<Link href="/rk2/signals/assignment">IO-Zuordnung</Link>
</ListItem>
<ListItem hover={true} >
<a href={Sites.rk2.signals.import.url}>{Sites.rk2.signals.import.name}</a>
</ListItem>
+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>;
}
+35
View File
@@ -0,0 +1,35 @@
import { IOType, type IoCreate } from "@/types/anlagen/ios";
import type { IoExcelRow } from "@/types/anlagen/signals";
// Wortadressen werden entsprechend dem Importformat als analoge IOs behandelt.
const typeMap: Record<string, IOType> = {
I: IOType.DIGITAL_INPUT,
Q: IOType.DIGITAL_OUTPUT,
IW: IOType.ANALOG_INPUT,
QW: IOType.ANALOG_OUTPUT,
...Object.fromEntries(Object.values(IOType).map((type) => [type, type])),
};
export function ioExcelRowsToIos(rows: IoExcelRow[]): IoCreate[] {
return rows.map((row, index) => {
const adrType = typeof row.adrType === 'string' && Object.hasOwn(typeMap, row.adrType)
? typeMap[row.adrType] : undefined;
if (!adrType) throw new Error(`Datensatz ${index + 1}: Unbekannter IO-Typ "${row.adrType}".`);
if (!Number.isInteger(row.adrByte) || row.adrByte < 0) {
throw new Error(`Datensatz ${index + 1}: Ungültige Byteadresse.`);
}
const digital = adrType === IOType.DIGITAL_INPUT || adrType === IOType.DIGITAL_OUTPUT;
if (digital && (!Number.isInteger(row.adrBit) || row.adrBit < 0 || row.adrBit > 7)) {
throw new Error(`Datensatz ${index + 1}: Die Bitadresse muss zwischen 0 und 7 liegen.`);
}
return {
adrType,
adrByte: row.adrByte,
adrBit: digital ? row.adrBit : undefined,
functionText: row.functionText ?? undefined,
seite: row.seite,
seiteName: row.seiteName ?? undefined,
excelData: JSON.stringify(row),
};
});
}
+37 -21
View File
@@ -10,47 +10,63 @@ export interface IoResponse {
id:string,
anlageId: string,
type: IOType,
address: number,
adrType: string,
adrByte: number,
adrBit?: number,
plcId?: string,
moduleId?: string,
channel?: number,
text?: string,
functionText?: string,
seite?: number,
seiteName?: string,
excelData?: string,
plcData?: string,
plcId?: string,
moduleId?: string,
channel?: number,
}
export interface IoCreate {
//anlageId: string,
type: IOType,
address: number,
adrType: string,
adrByte: number,
adrBit?: number,
plcId?: string,
moduleId?: string,
channel?: number,
text?: string,
functionText?: string,
seite?: number,
seiteName?: string,
excelData?: string,
plcData?: string,
plcId?: string,
moduleId?: string,
channel?: number,
}
export interface IoBulkUpdateResult {
matched: number;
modified: number;
unchanged: number;
missing: number;
duplicates: number;
}
export interface IoUpdate {
anlageId?: string,
type?: IOType,
address?: number,
adrType?: string,
adrByte?: number,
adrBit?: number,
plcId?: string,
moduleId?: string,
channel?: number,
text?: string,
functionText?: string,
seite?: number,
seiteName?: string,
excelData?: string,
plcData?: string,
plcId?: string | null,
moduleId?: string | null,
channel?: number,
}
//--- n.v.
+18
View File
@@ -35,3 +35,21 @@ export interface SignalUpdate {
ioId?: string,
componentId?: string,
}
export interface IoExcelData {
filename: string,
message: string,
size: number,
data: IoExcelRow[],
}
export interface IoExcelRow {
functionText: string,
seite: number,
seiteName: string,
adrType: string,
adrByte: number
adrBit: number,
spsKarte?: string,
}