diff --git a/src/actions/rk2/api-compTypes.ts b/src/actions/rk2/api-compTypes.ts index ec834fd..a6f3d67 100644 --- a/src/actions/rk2/api-compTypes.ts +++ b/src/actions/rk2/api-compTypes.ts @@ -176,6 +176,12 @@ export const componentTypeDefinitions: ComponentTypeDefinition[] = [ label: "Vorortbedienung", properties: [ + { + key: "ss_anwahl", + label: "Schalter Anwahl Vorort", + type: "boolean", + defaultValue: true, + }, { key: "ta_ein", label: "Ein Taster", @@ -252,10 +258,10 @@ export const componentDefaults: ComponentDefaults[] = [ signals: [ { name: "start", type: SignalType.DIGITAL_OUTPUT }, - { name: "startRtg2", type: SignalType.DIGITAL_OUTPUT }, +// { name: "startRtg2", type: SignalType.DIGITAL_OUTPUT }, { name: "rm", type: SignalType.DIGITAL_INPUT }, { name: "msOk", type: SignalType.DIGITAL_INPUT }, - { name: "tsOk", type: SignalType.DIGITAL_INPUT }, +// { name: "tsOk", type: SignalType.DIGITAL_INPUT }, { name: "ptcOk", type: SignalType.DIGITAL_INPUT }, ], }, @@ -315,7 +321,8 @@ export const componentDefaults: ComponentDefaults[] = [ name: "Vorort", signals: [ { name: "TaEin", type: SignalType.DIGITAL_INPUT }, - { name: "TaNichtAus", type: SignalType.DIGITAL_INPUT }, +// { name: "TaNichtAus", type: SignalType.DIGITAL_INPUT }, + { name: "SsAnwahl", type: SignalType.DIGITAL_INPUT }, ], }, diff --git a/src/actions/rk2/api-signals.ts b/src/actions/rk2/api-signals.ts index abe553d..9a2b8e6 100644 --- a/src/actions/rk2/api-signals.ts +++ b/src/actions/rk2/api-signals.ts @@ -25,6 +25,7 @@ export async function api_signal_assignIo(id: string, ioId: string | null): Prom } const data: SignalResponse = await response.json(); revalidatePath('/rk2/signals/assignment'); + revalidatePath('/rk2/signals/assignments'); return { success: true, data }; } catch { return { success: false, errors: ['IO-Zuordnung konnte nicht gespeichert werden.'] }; @@ -43,6 +44,7 @@ export async function api_signals_assignIos(assignments: { signalId: string; ioI } const data: SignalResponse[] = await response.json(); revalidatePath('/rk2/signals/assignment'); + revalidatePath('/rk2/signals/assignments'); return { success: true, data }; } catch { return { success: false, errors: ['Zuordnungen konnten nicht gespeichert werden.'] }; } } @@ -119,6 +121,7 @@ export async function api_signals_create(data: SignalCreate): Promise> { + try { + const response = await fetch(`${url_signals}/${encodeURIComponent(id)}`, { method: 'DELETE' }); + if (!response.ok) { + const body: unknown = await response.json().catch(() => null); + const message = typeof body === 'object' && body !== null && 'message' in body ? body.message : undefined; + return { success: false, errors: [typeof message === 'string' ? message : 'Signal konnte nicht gelöscht werden.'] }; + } + const data: SignalResponse = await response.json(); + if (data.componentId) revalidatePath(`${Sites.rk2.signals.url}/${data.componentId}`); + revalidatePath('/rk2/signals/assignment'); + revalidatePath('/rk2/signals/assignments'); + return { success: true, data }; + } catch { return { success: false, errors: ['Signal konnte nicht gelöscht werden.'] }; } +} + //----------------------------------------------------------------------------- //--- Upload EA Excel File //----------------------------------------------------------------------------- diff --git a/src/app/(pages)/rk2/page.tsx b/src/app/(pages)/rk2/page.tsx index cbdb954..b8f6282 100644 --- a/src/app/(pages)/rk2/page.tsx +++ b/src/app/(pages)/rk2/page.tsx @@ -1,3 +1,4 @@ +import { formatComponentName } from "@/lib/componentName"; import { Sites } from "@/_config/sites"; import { api_units } from "@/actions/rk2/api-units"; @@ -34,7 +35,7 @@ export default async function PageUnits() { {unit.type}
- {unit.components?.map((comp) =>
{comp.name}
)} + {unit.components?.map((comp) =>
{formatComponentName(comp)}
)}
+ + {exportError &&

{exportError}

} + +
+ + + {columns.map(({ key, label }) => ( + ))} + + {columns.map(({ key, label }) => )} + + {visible.map((row) => ( + + + + + + + + + + + ) + )} + +
+ {key === 'bit' ? label : } +
+ {key !== 'bit' && setFilters((current) => ({ ...current, [key]: event.target.value }))} />} +
{row.group}{row.bmk || '–'}{row.unitId ? {row.unit} : row.unit}{row.componentId ? {row.component} : row.component}{row.signal}{row.type}{row.byte ?? '–'}{row.bit ?? '–'}{row.functionText || '–'}
+ + {visible.length === 0 &&

Keine Zuordnungen passend zum Filter.

} + + ); +} diff --git a/src/components/rk2/signals/componentSignals.tsx b/src/components/rk2/signals/componentSignals.tsx new file mode 100644 index 0000000..fdb0112 --- /dev/null +++ b/src/components/rk2/signals/componentSignals.tsx @@ -0,0 +1,67 @@ +"use client"; + +import { useState } from "react"; +import { useRouter } from "next/navigation"; +import { api_signals_delete } from "@/actions/rk2/api-signals"; +import { Button } from "@/components/ui/button"; +import { SignalForm } from "./signalForm"; +import type { ComponentResponse } from "@/types/anlagen/components"; +import type { SignalResponse } from "@/types/anlagen/signals"; +import type { IoResponse } from "@/types/anlagen/ios"; + +interface Props { component: ComponentResponse; signals: SignalResponse[]; ios: IoResponse[]; anlageId: string } + +export default function ComponentSignals({ component, signals, ios, anlageId }: Props) { + const router = useRouter(); + const [editing, setEditing] = useState(); + const [deleting, setDeleting] = useState(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(''); + const [message, setMessage] = useState(''); + + const remove = async (id: string) => { + setBusy(true); + setError(''); + setMessage(''); + try { + const result = await api_signals_delete(id); + if (!result.success) { setError(result.errors.join(', ')); return; } + setDeleting(undefined); + setEditing(undefined); + setMessage('Signal gelöscht. Der IO bleibt erhalten.'); + router.refresh(); + } finally { setBusy(false); } + }; + + return
+

Vorhandene Signale ({signals.length})

+ {error &&

{error}

} + {message &&

{message}

} +
+ {['Name', 'Typ', 'Beschreibung', 'IO', 'Aktionen'].map((label) => )} + {signals.map((signal) => { + const io = ios.find((item) => item.id === signal.ioId && item.anlageId === anlageId); + return + + + + + + ; + })} +
{label}
{signal.name}{signal.type}{signal.description}{io ? `${io.adrType} ${io.adrByte}${io.adrBit == null ? '' : `.${io.adrBit}`} – ${io.functionText ?? ''}` : signal.ioId ? 'IO nicht verfügbar' : 'Nicht zugeordnet'}
+ + +
+ {deleting === signal.id &&
+

Signal „{signal.name}“ löschen? Der IO bleibt erhalten.

+ + +
}
{signals.length === 0 &&

Noch keine Signale angelegt.

}
+ {editing && signals.find((item) => item.id === editing) &&
+

Signal bearbeiten

+ item.id === editing)} onSaved={() => setEditing(undefined)} /> + +
} +
; +} diff --git a/src/components/rk2/signals/signalForm.tsx b/src/components/rk2/signals/signalForm.tsx index 29b39ec..18e46e8 100644 --- a/src/components/rk2/signals/signalForm.tsx +++ b/src/components/rk2/signals/signalForm.tsx @@ -1,6 +1,6 @@ "use client" -import { api_signals, api_signals_create } from "@/actions/rk2/api-signals"; +import { api_signals_create, api_signals_update } from "@/actions/rk2/api-signals"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; @@ -8,16 +8,22 @@ import { Select } from "@/components/ui/select"; import { useSignal } from "@/hooks/rk2/useSignal"; import { ComponentResponse } from "@/types/anlagen/components" import { SignalCreate, SignalResponse, SignalType } from "@/types/anlagen/signals" -import { useEffect } from "react"; +import { useEffect, useState } from "react"; +import { useRouter } from "next/navigation"; interface Props { componente: ComponentResponse, initSignal?: SignalResponse, + onSaved?: () => void, } -export function SignalForm({ componente, initSignal }: Props) { +export function SignalForm({ componente, initSignal, onSaved }: Props) { + const router = useRouter(); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(''); + const [message, setMessage] = useState(''); const { setSignal, setValue, signalData, string_to_signalType } = useSignal({}); @@ -27,34 +33,53 @@ export function SignalForm({ componente, initSignal }: Props) { }, [initSignal]); */ useEffect(() => { + if (initSignal) setSignal({ ...initSignal, componentId: componente.id }); setValue("componentId",componente.id); //if (initSignal) setSignal({...initSignal,componentId:componente.id}); // setSignal({componentId:componente.id}); - }, [componente]); + }, [componente, initSignal]); - const handlerSave = ()=>{ + const handlerSave = async ()=>{ + if (saving) return; + setError(''); + setMessage(''); + if (!signalData.name?.trim()) { setError('Bitte einen Signalnamen eingeben.'); return; } console.log("save") const saveData:SignalCreate ={ - componentId:signalData.componentId!, - name:signalData.name!, + componentId:componente.id, + name:signalData.name.trim(), description:signalData.description!, type:signalData.type!, } - api_signals_create(saveData); + setSaving(true); + try { + const result = initSignal + ? await api_signals_update(initSignal.id, saveData) + : await api_signals_create(saveData); + if (!result.success) { + setError(Array.isArray(result.errors) ? result.errors.join(', ') : String(result.errors)); + return; + } + setMessage(initSignal ? 'Signal geändert.' : 'Signal angelegt.'); + if (!initSignal) { setValue('name', ''); setValue('description', ''); } + router.refresh(); + onSaved?.(); + } catch { setError('Signal konnte nicht angelegt werden.'); } + finally { setSaving(false); } } return (
{/*---Form Data */} -
+
- setValue('name', e.target.value)} /> + setValue('name', e.target.value)} />
- setValue('type', string_to_signalType(e.target.value))} > @@ -63,19 +88,21 @@ export function SignalForm({ componente, initSignal }: Props) {
- setValue('description', e.target.value)} /> + setValue('description', e.target.value)} />
- -
+ + - {true && + {false &&
{JSON.stringify(signalData, null, 2)}
} + {error &&

{error}

} + {message &&

{message}

}
) } diff --git a/src/components/rk2/signals/signalIoAssignment.tsx b/src/components/rk2/signals/signalIoAssignment.tsx index 5a5c5e5..baea87d 100644 --- a/src/components/rk2/signals/signalIoAssignment.tsx +++ b/src/components/rk2/signals/signalIoAssignment.tsx @@ -1,6 +1,10 @@ "use client"; +import { formatComponentName } from "@/lib/componentName"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useAssignmentSession, type AssignmentSettings } from "@/hooks/rk2/useAssignmentSession"; import { api_signals_assignIos, api_signals } from "@/actions/rk2/api-signals"; import { Button } from "@/components/ui/button"; import IoFilter from "@/components/rk2/ios/ioFilter"; @@ -15,6 +19,7 @@ interface Props { signals: SignalResponse[]; ios: IoResponse[]; anlageId: string; + initialUnitId?: string; } function ioLabel(io: IoResponse) { @@ -34,27 +39,64 @@ function groupPath(id: string | undefined, groups: GroupResponse[]): string { return parts.join(' / ') || 'Unbekannte Gruppe'; } -export default function SignalIoAssignment({ groups, units, signals: initialSignals, ios, anlageId }: Props) { +export default function SignalIoAssignment({ groups, units, signals: initialSignals, ios, anlageId, initialUnitId }: 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 router = useRouter(); + const initialUnit = units.find((item) => item.id === initialUnitId); + const { settings, setSettings, ready, persist, storageError } = useAssignmentSession(`rk:io-assignment:${anlageId}`, { + unitId: initialUnit?.id ?? '', + signalId: initialSignals.find((item) => !item.ioId && item.anlageId === anlageId && initialUnit?.components.some((component) => component.id === item.componentId))?.id ?? '', + ioId: '', functionText: '', adrByte: '', hideAssigned: false, hideUsedIos: false, + ioSort: 'functionText', pending: {}, scroll: { units: 0, signals: 0, ios: 0, pending: 0 }, + }); + const { pending, unitId, signalId, ioId, functionText, adrByte, hideAssigned, hideUsedIos, ioSort } = settings; + const fieldSetter = (field: K) => + (value: AssignmentSettings[K] | ((previous: AssignmentSettings[K]) => AssignmentSettings[K])) => + setSettings((current) => ({ ...current, [field]: typeof value === 'function' + ? (value as (previous: AssignmentSettings[K]) => AssignmentSettings[K])(current[field]) : value })); + const setPending = fieldSetter('pending'), setUnitId = fieldSetter('unitId'), setSignalId = fieldSetter('signalId'); + const setIoId = fieldSetter('ioId'), setFunctionText = fieldSetter('functionText'), setAdrByte = fieldSetter('adrByte'); + const setHideAssigned = fieldSetter('hideAssigned'), setHideUsedIos = fieldSetter('hideUsedIos'), setIoSort = fieldSetter('ioSort'); + const effectiveSignals = signals.map((item) => Object.hasOwn(pending, item.id) ? { ...item, ioId: pending[item.id].ioId ?? undefined } : item); const pendingCount = Object.keys(pending).length; + const unitsRef = useRef(null), signalsRef = useRef(null); + const iosRef = useRef(null), pendingRef = useRef(null); + const restored = useRef(false); + const previousSelection = useRef(''); 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(''); + if (!ready || restored.current) return; + const selectedUnit = units.find((item) => item.id === (initialUnitId ?? settings.unitId)); + const restoredSignalId = initialUnitId && initialUnitId !== settings.unitId + ? signals.find((item) => !item.ioId && selectedUnit?.components.some((component) => component.id === item.componentId))?.id + : settings.signalId; + const selectedSignal = signals.find((item) => item.id === restoredSignalId && item.anlageId === anlageId + && selectedUnit?.components.some((component) => component.id === item.componentId)); + const validUnitId = selectedUnit?.id ?? '', validSignalId = selectedSignal?.id ?? ''; + setSettings((current) => ({ ...current, unitId: validUnitId, signalId: validSignalId, + ioId: ios.some((item) => item.id === current.ioId) ? current.ioId : '' })); + const frame = requestAnimationFrame(() => { + if (unitsRef.current) unitsRef.current.scrollTop = settings.scroll.units; + if (signalsRef.current) signalsRef.current.scrollTop = settings.scroll.signals; + if (iosRef.current) iosRef.current.scrollTop = settings.scroll.ios; + if (pendingRef.current) pendingRef.current.scrollTop = settings.scroll.pending; + previousSelection.current = validSignalId; + restored.current = true; + }); + return () => cancelAnimationFrame(frame); + }, [ready]); useEffect(() => { + if (!restored.current || previousSelection.current === signalId) return; + previousSelection.current = signalId; 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 snapshot = (): AssignmentSettings => ({ ...settings, scroll: { + units: unitsRef.current?.scrollTop ?? 0, signals: signalsRef.current?.scrollTop ?? 0, + ios: iosRef.current?.scrollTop ?? 0, pending: pendingRef.current?.scrollTop ?? 0, + } }); + const openUnit = () => { + if (!unitId || !persist(snapshot())) return; + router.push(`/rk2/units/edit/${encodeURIComponent(unitId)}?from=io-assignment`); + }; const [busy, setBusy] = useState(false); const [message, setMessage] = useState(''); const [error, setError] = useState(''); @@ -65,7 +107,7 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign 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 pendingIoIds = new Set(Object.values(pending).map((entry) => entry.ioId).filter((id): id is string => id !== null)); const textFilter = functionText.trim().toLocaleLowerCase('de'); const textTerms = textFilter.split(/\s+/).filter(Boolean); const byteFilter = adrByte.trim(); @@ -74,7 +116,13 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign && ((!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)); + .sort((a, b) => { + const addressOrder = a.adrType.localeCompare(b.adrType, 'de') + || a.adrByte - b.adrByte + || (a.adrBit ?? -1) - (b.adrBit ?? -1); + return ioSort === 'address' ? addressOrder + : (a.functionText ?? '').localeCompare(b.functionText ?? '', 'de', { numeric: true, sensitivity: 'base' }) || addressOrder; + }); const unitGroups = new Map(); for (const item of [...units].sort((a, b) => a.name.localeCompare(b.name, 'de', { numeric: true }))) { const key = item.groupId ?? ''; @@ -98,9 +146,9 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign 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; + const original = Object.hasOwn(items, signal.id) ? items[signal.id].previousIoId : signals.find((item) => item.id === signal.id)?.ioId ?? null; if (original === targetIoId) delete updated[signal.id]; - else updated[signal.id] = targetIoId; + else updated[signal.id] = { ioId: targetIoId, previousIoId: original }; return updated; }); setMessage(`Zuordnung für ${signal.name} vorgemerkt.`); @@ -134,7 +182,7 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign 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, + signalId: id, ioId: target.ioId, previousIoId: target.previousIoId, }))); if (!result.success) { setError(result.errors.join(', ')); return; } const saved = new Map(result.data.map((item) => [item.id, item])); @@ -147,13 +195,19 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign finally { setBusy(false); } }; + const conflicts = Object.entries(pending).filter(([id, entry]) => { + const item = signals.find((signal) => signal.id === id && signal.anlageId === anlageId); + return !item || (entry.ioId !== null && !ios.some((io) => io.id === entry.ioId)) + || ((item.ioId ?? null) !== entry.previousIoId && (item.ioId ?? null) !== entry.ioId); + }); + if (!ready) return

Einstellungen werden geladen…

; return
{pendingCount} Zuordnungen ausstehend
Signal: {signal ? `${unit?.name ?? ''} / ${signal.name}` : 'Bitte auswählen'}
IO: {selectedIo ? ioLabel(selectedIo) : 'Bitte auswählen'}
- @@ -169,15 +223,18 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign const target = orderedUnits[orderedUnits.findIndex((item) => item.id === unitId) + 1]; if (target) chooseUnit(target); }}>Nächste Unit + {unit && }
{occupied &&

Dieser IO ist bereits einem anderen Signal zugeordnet.

} + {storageError &&

{storageError}

} + {conflicts.length > 0 &&

{conflicts.length} Vormerkungen betreffen gelöschte oder geänderte Daten. Bitte prüfen oder zurücknehmen.

} {error &&

{error}

} {message &&

{message}

}

Units nach Gruppe

-
+
{ const top = event.currentTarget.scrollTop; if (restored.current) setSettings((s) => ({ ...s, scroll: { ...s.scroll, units: top } })); }}> {sortedGroups.map(([id, items]) =>

{groupPath(id, groups)}

{items.map((item) =>

Vormerkungen ({pendingCount})

- {pendingCount > 0 &&
- {Object.entries(pending).map(([id, targetIoId]) => { + {pendingCount > 0 &&
{ const top = event.currentTarget.scrollTop; if (restored.current) setSettings((s) => ({ ...s, scroll: { ...s.scroll, pending: top } })); }} className="max-h-[65vh] overflow-y-auto"> + {Object.entries(pending).map(([id, assignment]) => { + const targetIoId = assignment.ioId; 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}
+
{targetUnit?.name} / {component ? formatComponentName(component) : ''}
{item?.name ?? id} → {targetIoId === null ? 'Zuordnung entfernen' : targetIo ? ioLabel(targetIo) : targetIoId}
diff --git a/src/components/rk2/units/componentForm.tsx b/src/components/rk2/units/componentForm.tsx index 92a6421..82eaf67 100644 --- a/src/components/rk2/units/componentForm.tsx +++ b/src/components/rk2/units/componentForm.tsx @@ -1,4 +1,5 @@ "use client" +import Link from "next/link"; import { PropertyField } from "./propertyFields" import { ComponentDefaults, ComponentResponse, ComponentType, ComponentTypeDefinition } from "@/types/anlagen/components" @@ -112,6 +113,7 @@ export function ComponentForm({ component, componentTypes, componentDefaults, on {/* --- Signal IDs ----*/} + Signale verwalten {signalByComp && signalByComp.map((s) =>
{s.name}
)} @@ -129,4 +131,4 @@ export function ComponentForm({ component, componentTypes, componentDefaults, on } /* -*/ \ No newline at end of file +*/ diff --git a/src/components/rk2/units/unitEdit.tsx b/src/components/rk2/units/unitEdit.tsx index 596e86c..653b4ed 100644 --- a/src/components/rk2/units/unitEdit.tsx +++ b/src/components/rk2/units/unitEdit.tsx @@ -15,6 +15,7 @@ import { ComponentDefaults, ComponentTypeDefinition } from "@/types/anlagen/comp interface Params { + initialComponentId?: string; anlage: Anlage, groups: GroupResponse[], selectedUnit?: UnitResponse, @@ -22,7 +23,7 @@ interface Params { componentDefaults: ComponentDefaults[] } -export const UnitEdit = ({ anlage, groups, selectedUnit, componentTypes,componentDefaults }: Params) => { +export const UnitEdit = ({ anlage, groups, selectedUnit, componentTypes,componentDefaults, initialComponentId }: Params) => { const { getGroupById } = useGroups({ groups }); @@ -55,7 +56,7 @@ export const UnitEdit = ({ anlage, groups, selectedUnit, componentTypes,componen return (
- setShowSelectGroup(true)} unitIntial={selectedUnit} componentTypes={componentTypes} componentDefaults={componentDefaults}/> + setShowSelectGroup(true)} unitIntial={selectedUnit} componentTypes={componentTypes} componentDefaults={componentDefaults} initialComponentId={initialComponentId}/> {showSelectGroup && setShowSelectGroup(false)} > diff --git a/src/components/rk2/units/unit_createForm.tsx b/src/components/rk2/units/unit_createForm.tsx index c339c49..546524d 100644 --- a/src/components/rk2/units/unit_createForm.tsx +++ b/src/components/rk2/units/unit_createForm.tsx @@ -1,4 +1,5 @@ "use client"; +import { formatComponentName } from "@/lib/componentName"; import { useEffect, useState } from "react" import { Anlage } from "@/types/rk"; @@ -21,6 +22,7 @@ import { Select } from "@/components/ui/select"; interface Params { + initialComponentId?: string; anlage: Anlage, unitIntial?: UnitResponse selectedGroup?: GroupResponse @@ -30,9 +32,9 @@ interface Params { debug?: boolean } -export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selectedGroup, componentTypes, componentDefaults, debug }: Params) => { +export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selectedGroup, componentTypes, componentDefaults, debug, initialComponentId }: Params) => { const [id, setId] = useState(); - const [selectedComponent, setSelectedComponent] = useState(); + const [selectedComponent, setSelectedComponent] = useState(() => unitIntial?.components.find((component) => component.id === initialComponentId)); const { emptyUnit, unitType, setValue, unitData, string_to_UnitType } = useUnit({ unit: unitIntial }); @@ -163,7 +165,7 @@ export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selec {componentNames.map((comp) => ( - + ))} @@ -189,10 +191,7 @@ export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selec - {c.prefix && c.prefix} - {c.name} - {c.postfix && c.postfix} - {c.index && c.index > 0 ? c.index: ""} + {formatComponentName(c)} @@ -277,4 +276,4 @@ export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selec )} -*/ \ No newline at end of file +*/ diff --git a/src/hooks/rk2/useAssignmentSession.ts b/src/hooks/rk2/useAssignmentSession.ts new file mode 100644 index 0000000..165f1c2 --- /dev/null +++ b/src/hooks/rk2/useAssignmentSession.ts @@ -0,0 +1,56 @@ +"use client"; + +import { useCallback, useEffect, useRef, useState } from "react"; + +export interface PendingAssignment { ioId: string | null; previousIoId: string | null } +export interface AssignmentSettings { + unitId: string; signalId: string; ioId: string; + functionText: string; adrByte: string; + hideAssigned: boolean; hideUsedIos: boolean; + ioSort: 'functionText' | 'address'; + pending: Record; + scroll: Record<'units' | 'signals' | 'ios' | 'pending', number>; +} + +export function isAssignmentSettings(value: unknown): value is AssignmentSettings { + if (!value || typeof value !== 'object') return false; + const v = value as Record; + if (!['unitId', 'signalId', 'ioId', 'functionText', 'adrByte'].every((key) => typeof v[key] === 'string') + || typeof v.hideAssigned !== 'boolean' || typeof v.hideUsedIos !== 'boolean' + || !['functionText', 'address'].includes(String(v.ioSort))) return false; + if (!v.pending || typeof v.pending !== 'object' || Array.isArray(v.pending) + || !v.scroll || typeof v.scroll !== 'object') return false; + const scroll = v.scroll as Record; + if (!['units', 'signals', 'ios', 'pending'].every((key) => typeof scroll[key] === 'number' && Number.isFinite(scroll[key]) && scroll[key] >= 0)) return false; + return Object.values(v.pending).every((entry) => { + if (!entry || typeof entry !== 'object') return false; + const p = entry as Record; + return (p.ioId === null || typeof p.ioId === 'string') && (p.previousIoId === null || typeof p.previousIoId === 'string'); + }); +} + +export function useAssignmentSession(key: string, initial: AssignmentSettings) { + const [settings, setSettings] = useState(initial); + const [ready, setReady] = useState(false); + const [storageError, setStorageError] = useState(''); + const initialRef = useRef(initial); + useEffect(() => { + try { + const raw = sessionStorage.getItem(key); + const value: unknown = raw ? JSON.parse(raw) : null; + if (value && typeof value === 'object' && 'version' in value && value.version === 1 + && 'settings' in value && isAssignmentSettings(value.settings)) setSettings(value.settings); + else setSettings(initialRef.current); + } catch { setStorageError('Gespeicherte Einstellungen konnten nicht geladen werden.'); } + setReady(true); + }, [key]); + const persist = useCallback((value: AssignmentSettings) => { + try { + sessionStorage.setItem(key, JSON.stringify({ version: 1, settings: value })); + setStorageError(''); + return true; + } catch { setStorageError('Einstellungen konnten nicht im Browser gespeichert werden.'); return false; } + }, [key]); + useEffect(() => { if (ready) persist(settings); }, [settings, ready, persist]); + return { settings, setSettings, ready, persist, storageError }; +} diff --git a/src/lib/componentName.ts b/src/lib/componentName.ts new file mode 100644 index 0000000..9fb8380 --- /dev/null +++ b/src/lib/componentName.ts @@ -0,0 +1,10 @@ +interface ComponentNameParts { + name: string; + prefix?: string; + index?: number; + postfix?: string; +} + +export function formatComponentName(component: ComponentNameParts): string { + return `${component.prefix ?? ''}${component.name}${component.index !== undefined && component.index > 0 ? component.index : ''}${component.postfix ?? ''}`; +} diff --git a/src/lib/ioEaExport.ts b/src/lib/ioEaExport.ts new file mode 100644 index 0000000..bd45e8f --- /dev/null +++ b/src/lib/ioEaExport.ts @@ -0,0 +1,42 @@ +import type { ComponentResponse } from "@/types/anlagen/components"; +import type { UnitResponse } from "@/types/anlagen/units"; + +export function eaName(unit: UnitResponse, component: ComponentResponse, signal: string): string { + const componentName = `${component.name}${(component.index ?? 0) > 0 ? component.index : ''}`; + return [unit.prefix, unit.bmk, unit.name, unit.postfix, component.prefix, componentName, component.postfix, signal] + .map((part) => part?.trim()).filter(Boolean).join('_'); +} + +export interface EaSource { + exportName: string; + variableTable: string; + exportComment: string; + type: string; + byte?: number; + bit?: number; +} + +const addressTypes: Record = { + I: 'I', Q: 'Q', IW: 'IW', QW: 'QW', + DigitalInput: 'I', DigitalOutput: 'Q', AnalogInput: 'IW', AnalogOutput: 'QW', +}; + +export function createEaCsv(rows: EaSource[]): string { + const names = new Set(); + const records = rows.map((row) => { + const type = addressTypes[row.type]; + const digital = type === 'I' || type === 'Q'; + if (!row.exportName || !row.variableTable || !type || !Number.isInteger(row.byte) || row.byte! < 0 + || (digital && (!Number.isInteger(row.bit) || row.bit! < 0 || row.bit! > 7))) { + throw new Error(`Unvollständige Exportdaten für "${row.exportName || 'unbekanntes Signal'}".`); + } + if (names.has(row.exportName.toLocaleLowerCase('de'))) { + throw new Error(`Der Variablenname "${row.exportName}" kommt mehrfach vor.`); + } + names.add(row.exportName.toLocaleLowerCase('de')); + return [row.exportName, row.variableTable, digital ? 'Bool' : 'Word', + `%${type}${row.byte}${digital ? `.${row.bit}` : ''}`, row.exportComment]; + }); + return '\uFEFF' + [['Name', 'Variablentabelle', 'Datentyp', 'Adresse', 'Kommentar'], ...records] + .map((record) => record.map((value) => `"${value.replace(/"/g, '""')}"`).join(';')).join('\r\n'); +}