diff --git a/src/actions/rk2/api-compTypes.ts b/src/actions/rk2/api-compTypes.ts index a51a056..ec834fd 100644 --- a/src/actions/rk2/api-compTypes.ts +++ b/src/actions/rk2/api-compTypes.ts @@ -42,6 +42,14 @@ export const componentTypeDefinitions: ComponentTypeDefinition[] = [ defaultValue: true, required: false, }, + { + key: "rmRtg2", + label: "RueckmeldungRtg2", + type: "boolean", + defaultValue: false, + required: false, + }, + { key: "ms", label: "Motorschutz", diff --git a/src/actions/rk2/api-ios.ts b/src/actions/rk2/api-ios.ts index 51eda06..d20ba43 100644 --- a/src/actions/rk2/api-ios.ts +++ b/src/actions/rk2/api-ios.ts @@ -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(url: string, options: RequestInit): Promise> { + 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 { - - const result = await fetch(`${url_ios}`, { - method: 'GET', - headers: { 'Content-Type': 'application/json' } - }); - - const data = await result.json(); - - return data; + const result = await requestIo(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> { - - 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(`${url_ios}/${encodeURIComponent(id)}`, { method: 'GET' }); } -//----------------------------------------------------------------------------- -//--- ios CREATE -//----------------------------------------------------------------------------- -export async function api_ios_create(data: IoResponse): Promise> { - - const result = await fetch(`${url_ios}`, { +export async function api_ios_create(data: IoCreate): Promise> { + const result = await requestIo(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> { +export async function api_ios_bulkCreate(data: IoCreate[]): Promise> { + const result = await requestIo(`${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> { + const result = await requestIo(`${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> { + const result = await requestIo(`${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> { + const result = await requestIo(`${url_ios}/${encodeURIComponent(id)}`, { method: 'DELETE' }); + if (result.success) revalidatePath(Sites.rk2.ios.url); + return result; +} diff --git a/src/actions/rk2/api-signals.ts b/src/actions/rk2/api-signals.ts index 34e0a99..abe553d 100644 --- a/src/actions/rk2/api-signals.ts +++ b/src/actions/rk2/api-signals.ts @@ -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> { + 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> { + 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 { 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> { +export async function api_signals_excel_upload(formData:any): Promise> { const result = await fetch(`${url_signals}/upload`, { method: 'POST', diff --git a/src/app/(pages)/rk2/signals/assignment/page.tsx b/src/app/(pages)/rk2/signals/assignment/page.tsx new file mode 100644 index 0000000..1877552 --- /dev/null +++ b/src/app/(pages)/rk2/signals/assignment/page.tsx @@ -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
+ + unit.anlageId === anlage.id)} + signals={signals} ios={ios.filter((io) => io.anlageId === anlage.id)} anlageId={anlage.id} /> +
; +} diff --git a/src/app/(pages)/rk2/signals/import/page.tsx b/src/app/(pages)/rk2/signals/import/page.tsx index b1fd663..c87feca 100644 --- a/src/app/(pages)/rk2/signals/import/page.tsx +++ b/src/app/(pages)/rk2/signals/import/page.tsx @@ -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 */} -
- +
+
diff --git a/src/app/(pages)/rk2/signals/page.tsx b/src/app/(pages)/rk2/signals/page.tsx index b3f7d85..1c605d8 100644 --- a/src/app/(pages)/rk2/signals/page.tsx +++ b/src/app/(pages)/rk2/signals/page.tsx @@ -24,6 +24,9 @@ export default async function PageSignale() {
+ + IO-Zuordnung + {Sites.rk2.signals.import.name} diff --git a/src/components/rk2/ios/ioExcelCompare.tsx b/src/components/rk2/ios/ioExcelCompare.tsx new file mode 100644 index 0000000..88e027e --- /dev/null +++ b/src/components/rk2/ios/ioExcelCompare.tsx @@ -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([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(); + 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(); + for (const io of ios) { + const key = addressKey(io); + ioMap.set(key, [...(ioMap.get(key) ?? []), io]); + } + const compared = excel.flatMap((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
+ +
+

Excel / IO Vergleich

+ +
+ +
+ Rot: Unterschiede + Blau: In Excel nicht vorhanden + Gelb: In IOs nicht vorhanden +
+ + {loading &&

IO-Daten werden geladen…

} + + {(error || conversionError) &&

{error ?? conversionError}

} + + {!loading && !error && !conversionError &&
+ + + + + + + {fields.map((field) => )} + + + {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 + + + + {fields.map((field) => )} + ; + })} +
StatusTypAdresse{labels[field]}
Excel / IO
{status}{address.adrType} {address.adrByte}.{address.adrBit ?? '–'} +
Excel: {pair.excel?.[field] ?? '–'}
+
IO: {pair.io?.[field] ?? '–'}
+
+ {allRows.length === 0 &&

Keine Datensätze vorhanden.

} +
} +
; +} diff --git a/src/components/rk2/ios/ioExcelImport.tsx b/src/components/rk2/ios/ioExcelImport.tsx new file mode 100644 index 0000000..e8426c2 --- /dev/null +++ b/src/components/rk2/ios/ioExcelImport.tsx @@ -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(); + const [isSaving, setIsSaving] = useState(false); + const [uploadVersion, setUploadVersion] = useState(0); + + return ( +
+
+ { + setData(loaded); + setUploadVersion((version) => version + 1); + }} /> +
+ {data &&
+ + + {data.data.length === 0 &&

Keine Datensätze gefunden.

} + + {data.data.map((row, index) =>
+
{row.functionText}
+
{row.adrType}
+
{row.adrByte}
+
{row.adrBit}
+
{row.seite}
+
{row.seiteName}
+
{row.spsKarte}
+
)} +
} +
+ ); +} diff --git a/src/components/rk2/ios/ioExcelSave.tsx b/src/components/rk2/ios/ioExcelSave.tsx new file mode 100644 index 0000000..f990a5e --- /dev/null +++ b/src/components/rk2/ios/ioExcelSave.tsx @@ -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(); + const [errors, setErrors] = useState([]); + const [updateMessage, setUpdateMessage] = useState(); + + 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
+ + + {savedCount !== undefined &&

{savedCount} IO-Datensätze gespeichert, {rows.length - savedCount} vorhandene oder doppelte Datensätze übersprungen.

} + {updateMessage &&

{updateMessage}

} + {errors.length > 0 &&
{errors.map((error, index) =>

{error}

)}
} +
; +} diff --git a/src/components/rk2/ios/ioExcelUpload.tsx b/src/components/rk2/ios/ioExcelUpload.tsx new file mode 100644 index 0000000..696d8c3 --- /dev/null +++ b/src/components/rk2/ios/ioExcelUpload.tsx @@ -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(null); + const [error, setError] = useState(); + 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 ( +
+ + setFile(e.target.files?.[0] ?? null) + } + /> + + + {error &&

{error}

} + +
+ ); +} + +/* + +{data && JSON.stringify(data)} +*/ diff --git a/src/components/rk2/ios/ioFilter.tsx b/src/components/rk2/ios/ioFilter.tsx new file mode 100644 index 0000000..70e5fca --- /dev/null +++ b/src/components/rk2/ios/ioFilter.tsx @@ -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
+

Treffer im Funktionstext oder in der Byteadresse.

+

Mehrere Textbegriffe mit Leerzeichen trennen: Alle Begriffe müssen vorkommen.

+ + +
; +} diff --git a/src/components/rk2/signals/signalExcelUpload.tsx b/src/components/rk2/signals/signalExcelUpload.tsx deleted file mode 100644 index 44d161c..0000000 --- a/src/components/rk2/signals/signalExcelUpload.tsx +++ /dev/null @@ -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(null); - const [data, setData] = useState(); - - 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 ( -
- - setFile(e.target.files?.[0] ?? null) - } - /> - - - {data &&
{JSON.stringify(data,null,2)}
} -
- ); -} \ No newline at end of file diff --git a/src/components/rk2/signals/signalIoAssignment.tsx b/src/components/rk2/signals/signalIoAssignment.tsx new file mode 100644 index 0000000..5a5c5e5 --- /dev/null +++ b/src/components/rk2/signals/signalIoAssignment.tsx @@ -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(); + 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>({}); + 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(); + 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(); + 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
+
+
{pendingCount} Zuordnungen ausstehend
+
Signal: {signal ? `${unit?.name ?? ''} / ${signal.name}` : 'Bitte auswählen'}
+
IO: {selectedIo ? ioLabel(selectedIo) : 'Bitte auswählen'}
+
+ + + + +
+ {occupied &&

Dieser IO ist bereits einem anderen Signal zugeordnet.

} + {error &&

{error}

} + {message &&

{message}

} +
+
+
+

Units nach Gruppe

+
+ {sortedGroups.map(([id, items]) =>
+

{groupPath(id, groups)}

+ {items.map((item) => )} +
)} + {units.length === 0 &&

Keine Units vorhanden.

} +
+
+
+

Signale {unit && `– ${unit.name}`}

+ + {!unit &&

Unit auswählen, dann ein IO anklicken. Das nächste freie Signal wird automatisch ausgewählt.

} +
{ + 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
+

{component.name}

+ {items.map((item) => { + const current = ios.find((io) => io.id === item.ioId); + return ; + })} + {items.length === 0 &&

Keine Signale.

} +
; + })} + {unit?.components.length === 0 &&

Keine Komponenten vorhanden.

} +
+
+
+

IOs der Anlage ({visibleIos.length})

+ + +
+ {visibleIos.map((io) => { + const ownerList = owners.get(io.id) ?? []; + const taken = ownerList.some((item) => item.id !== signalId); + return ; + })} + {visibleIos.length === 0 &&

Keine IOs passend zum Filter.

} +
+
+
+

Vormerkungen ({pendingCount})

+ {pendingCount > 0 &&
+ {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
+
+
{targetUnit?.name} / {component?.name}
+
{item?.name ?? id} → {targetIoId === null ? 'Zuordnung entfernen' : targetIo ? ioLabel(targetIo) : targetIoId}
+
+ +
; + })} +
} + {pendingCount === 0 &&

Noch keine Zuordnungen vorgemerkt.

} +
+
+
; +} diff --git a/src/lib/ioExcelToIos.ts b/src/lib/ioExcelToIos.ts new file mode 100644 index 0000000..6313232 --- /dev/null +++ b/src/lib/ioExcelToIos.ts @@ -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 = { + 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), + }; + }); +} diff --git a/src/types/anlagen/ios.ts b/src/types/anlagen/ios.ts index 1086f84..18be9f4 100644 --- a/src/types/anlagen/ios.ts +++ b/src/types/anlagen/ios.ts @@ -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. diff --git a/src/types/anlagen/signals.ts b/src/types/anlagen/signals.ts index c094498..5f46320 100644 --- a/src/types/anlagen/signals.ts +++ b/src/types/anlagen/signals.ts @@ -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, + +}