io zuordnung; signal liste mit eas; links; csv ausgabe
This commit is contained in:
1 parent
13bbd26ce5
commit
f769ff7cc0
20 files changed
+590
-111
No files matched your search
@@ -176,6 +176,12 @@ export const componentTypeDefinitions: ComponentTypeDefinition[] = [
|
|||||||
label: "Vorortbedienung",
|
label: "Vorortbedienung",
|
||||||
|
|
||||||
properties: [
|
properties: [
|
||||||
|
{
|
||||||
|
key: "ss_anwahl",
|
||||||
|
label: "Schalter Anwahl Vorort",
|
||||||
|
type: "boolean",
|
||||||
|
defaultValue: true,
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: "ta_ein",
|
key: "ta_ein",
|
||||||
label: "Ein Taster",
|
label: "Ein Taster",
|
||||||
@@ -252,10 +258,10 @@ export const componentDefaults: ComponentDefaults[] = [
|
|||||||
|
|
||||||
signals: [
|
signals: [
|
||||||
{ name: "start", type: SignalType.DIGITAL_OUTPUT },
|
{ 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: "rm", type: SignalType.DIGITAL_INPUT },
|
||||||
{ name: "msOk", 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 },
|
{ name: "ptcOk", type: SignalType.DIGITAL_INPUT },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -315,7 +321,8 @@ export const componentDefaults: ComponentDefaults[] = [
|
|||||||
name: "Vorort",
|
name: "Vorort",
|
||||||
signals: [
|
signals: [
|
||||||
{ name: "TaEin", type: SignalType.DIGITAL_INPUT },
|
{ name: "TaEin", type: SignalType.DIGITAL_INPUT },
|
||||||
{ name: "TaNichtAus", type: SignalType.DIGITAL_INPUT },
|
// { name: "TaNichtAus", type: SignalType.DIGITAL_INPUT },
|
||||||
|
{ name: "SsAnwahl", type: SignalType.DIGITAL_INPUT },
|
||||||
],
|
],
|
||||||
|
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ export async function api_signal_assignIo(id: string, ioId: string | null): Prom
|
|||||||
}
|
}
|
||||||
const data: SignalResponse = await response.json();
|
const data: SignalResponse = await response.json();
|
||||||
revalidatePath('/rk2/signals/assignment');
|
revalidatePath('/rk2/signals/assignment');
|
||||||
|
revalidatePath('/rk2/signals/assignments');
|
||||||
return { success: true, data };
|
return { success: true, data };
|
||||||
} catch {
|
} catch {
|
||||||
return { success: false, errors: ['IO-Zuordnung konnte nicht gespeichert werden.'] };
|
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();
|
const data: SignalResponse[] = await response.json();
|
||||||
revalidatePath('/rk2/signals/assignment');
|
revalidatePath('/rk2/signals/assignment');
|
||||||
|
revalidatePath('/rk2/signals/assignments');
|
||||||
return { success: true, data };
|
return { success: true, data };
|
||||||
} catch { return { success: false, errors: ['Zuordnungen konnten nicht gespeichert werden.'] }; }
|
} catch { return { success: false, errors: ['Zuordnungen konnten nicht gespeichert werden.'] }; }
|
||||||
}
|
}
|
||||||
@@ -119,6 +121,7 @@ export async function api_signals_create(data: SignalCreate): Promise<ActionResu
|
|||||||
}
|
}
|
||||||
|
|
||||||
revalidatePath(Sites.rk2.signals.url + "/")
|
revalidatePath(Sites.rk2.signals.url + "/")
|
||||||
|
if (data.componentId) revalidatePath(`${Sites.rk2.signals.url}/${data.componentId}`);
|
||||||
return { success: true, data:resultData };
|
return { success: true, data:resultData };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -143,9 +146,28 @@ export async function api_signals_update(id:string,data: SignalCreate): Promise<
|
|||||||
}
|
}
|
||||||
|
|
||||||
revalidatePath(Sites.rk2.signals.url)
|
revalidatePath(Sites.rk2.signals.url)
|
||||||
|
if (data.componentId) revalidatePath(`${Sites.rk2.signals.url}/${data.componentId}`);
|
||||||
|
revalidatePath('/rk2/signals/assignment');
|
||||||
|
revalidatePath('/rk2/signals/assignments');
|
||||||
return { success: true, data:resultData };
|
return { success: true, data:resultData };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function api_signals_delete(id: string): Promise<ActionResult<SignalResponse>> {
|
||||||
|
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
|
//--- Upload EA Excel File
|
||||||
//-----------------------------------------------------------------------------
|
//-----------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { formatComponentName } from "@/lib/componentName";
|
||||||
import { Sites } from "@/_config/sites";
|
import { Sites } from "@/_config/sites";
|
||||||
import { api_units } from "@/actions/rk2/api-units";
|
import { api_units } from "@/actions/rk2/api-units";
|
||||||
|
|
||||||
@@ -34,7 +35,7 @@ export default async function PageUnits() {
|
|||||||
{unit.type}
|
{unit.type}
|
||||||
</div>
|
</div>
|
||||||
<div className="w-40">
|
<div className="w-40">
|
||||||
{unit.components?.map((comp) => <div key={comp.id}><div>{comp.name}</div></div>)}
|
{unit.components?.map((comp) => <div key={comp.id}><div>{formatComponentName(comp)}</div></div>)}
|
||||||
</div>
|
</div>
|
||||||
<ListItemAction>
|
<ListItemAction>
|
||||||
<Button variant={"secondary"} size={"xs"} >
|
<Button variant={"secondary"} size={"xs"} >
|
||||||
|
|||||||
@@ -1,47 +1,47 @@
|
|||||||
import { Sites } from "@/_config/sites";
|
import { formatComponentName } from "@/lib/componentName";
|
||||||
|
import Link from "next/link";
|
||||||
import { api_anlage_getSelected } from "@/actions/rk/api-anlage";
|
import { api_anlage_getSelected } from "@/actions/rk/api-anlage";
|
||||||
import { api_component_byId } from "@/actions/rk2/api-component";
|
import { api_component_byId } from "@/actions/rk2/api-component";
|
||||||
import { componentTypeDefinitions } from "@/actions/rk2/api-compTypes";
|
import { api_units_byId } from "@/actions/rk2/api-units";
|
||||||
|
import { api_groups } from "@/actions/rk2/api-groups";
|
||||||
|
import { api_signalsByComp } from "@/actions/rk2/api-signals";
|
||||||
|
import { api_ios } from "@/actions/rk2/api-ios";
|
||||||
|
import ComponentSignals from "@/components/rk2/signals/componentSignals";
|
||||||
import { SignalForm } from "@/components/rk2/signals/signalForm";
|
import { SignalForm } from "@/components/rk2/signals/signalForm";
|
||||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
|
||||||
import { Link } from "lucide-react";
|
|
||||||
|
|
||||||
type Props = {
|
|
||||||
params: Promise<{
|
|
||||||
componentId: string;
|
|
||||||
}>;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
export default async function PageSignalsEdit({ params }: Props) {
|
|
||||||
|
|
||||||
|
export default async function PageSignalsEdit({ params }: { params: Promise<{ componentId: string }> }) {
|
||||||
const { componentId } = await params;
|
const { componentId } = await params;
|
||||||
const resultComponentOfId = await api_component_byId(componentId);
|
const result = await api_component_byId(componentId);
|
||||||
const currentAnlage= await api_anlage_getSelected();
|
if (!result.success) return <div className="m-4"><p role="alert">Komponente konnte nicht geladen werden.</p><Link href="/rk2/signals">Zur Signalübersicht</Link></div>;
|
||||||
const componentTypes = componentTypeDefinitions;
|
const { component, unitId } = result.data;
|
||||||
|
const [anlage, unitResult, groups, signals, ios] = await Promise.all([
|
||||||
if(!resultComponentOfId) return <div>Keine Daten</div>
|
api_anlage_getSelected(), api_units_byId(unitId), api_groups(), api_signalsByComp(componentId), api_ios(),
|
||||||
return (
|
]);
|
||||||
<div className="">
|
if (!unitResult.success) return <p className="m-4" role="alert">Unit konnte nicht geladen werden.</p>;
|
||||||
<Link href={Sites.main.url}>{Sites.main.name}</Link>
|
const unit = unitResult.data;
|
||||||
<Link href={Sites.procon.url}>{Sites.procon.name}</Link>
|
if (unit.anlageId !== anlage.id) return <p className="m-4" role="alert">Die Komponente gehört nicht zur ausgewählten Anlage.</p>;
|
||||||
<div className="flex flex-col m-4 w-300 ">
|
const groupNames: string[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
<SignalForm componente={resultComponentOfId.data.component} ></SignalForm>
|
let group = groups.find((item) => item.id === unit.groupId);
|
||||||
|
while (group && !seen.has(group.id)) {
|
||||||
{true &&
|
seen.add(group.id);
|
||||||
<Card positons={"start"}>
|
groupNames.unshift(`${group.nr} ${group.name}`.trim());
|
||||||
<CardHeader variant={"danger"} >Debug</CardHeader>
|
group = groups.find((item) => item.id === group?.parentId);
|
||||||
<CardContent className="ps-8">
|
|
||||||
{componentId}
|
|
||||||
<pre>{JSON.stringify(resultComponentOfId, null, 2)}</pre>
|
|
||||||
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
}
|
}
|
||||||
|
return <div className="m-4">
|
||||||
</div>
|
<Breadcrumbs items={[
|
||||||
</div>
|
{ label: 'Signale', href: '/rk2/signals' },
|
||||||
);
|
{ label: `${anlage.anlageNr} ${anlage.name}` },
|
||||||
|
{ label: groupNames.join(' / ') || 'Ohne Gruppe' },
|
||||||
|
{ label: unit.name, href: `/rk2/units/edit/${encodeURIComponent(unit.id)}` },
|
||||||
|
{ label: formatComponentName(component) },
|
||||||
|
]} />
|
||||||
|
<h1 className="my-4 text-xl font-semibold">Signale: {unit.name} / {formatComponentName(component)}</h1>
|
||||||
|
<Link className="mb-4 mr-4 inline-block underline" href={`/rk2/units/edit/${encodeURIComponent(unitId)}?componentId=${encodeURIComponent(componentId)}`}>Zurück zur Komponente {formatComponentName(component)}</Link>
|
||||||
|
<Link className="mb-4 inline-block underline" href={`/rk2/signals/assignment?unitId=${encodeURIComponent(unitId)}`}>IOs zuordnen</Link>
|
||||||
|
<ComponentSignals component={component} signals={signals} ios={ios} anlageId={anlage.id} />
|
||||||
|
<h2 className="mb-2 font-semibold">Neues Signal</h2>
|
||||||
|
<SignalForm componente={component} />
|
||||||
|
</div>;
|
||||||
}
|
}
|
||||||
@@ -6,12 +6,13 @@ import { api_ios } from "@/actions/rk2/api-ios";
|
|||||||
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
|
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
|
||||||
import SignalIoAssignment from "@/components/rk2/signals/signalIoAssignment";
|
import SignalIoAssignment from "@/components/rk2/signals/signalIoAssignment";
|
||||||
|
|
||||||
export default async function AssignmentPage() {
|
export default async function AssignmentPage({ searchParams }: { searchParams: Promise<{ unitId?: string }> }) {
|
||||||
|
const { unitId } = await searchParams;
|
||||||
const anlage = await api_anlage_getSelected();
|
const anlage = await api_anlage_getSelected();
|
||||||
const [groups, units, signals, ios] = await Promise.all([api_groups(), api_units(), api_signals(), api_ios()]);
|
const [groups, units, signals, ios] = await Promise.all([api_groups(), api_units(), api_signals(), api_ios()]);
|
||||||
return <div className="m-4">
|
return <div className="m-4">
|
||||||
<Breadcrumbs items={[{ label: 'Signale', href: '/rk2/signals' }, { label: 'IO-Zuordnung' }, { label: `${anlage.anlageNr} ${anlage.name}` }]} />
|
<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)}
|
<SignalIoAssignment key={`${anlage.id}:${unitId ?? ''}`} groups={groups} units={units.filter((unit) => unit.anlageId === anlage.id)}
|
||||||
signals={signals} ios={ios.filter((io) => io.anlageId === anlage.id)} anlageId={anlage.id} />
|
signals={signals} ios={ios.filter((io) => io.anlageId === anlage.id)} anlageId={anlage.id} initialUnitId={unitId} />
|
||||||
</div>;
|
</div>;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import AssignmentsTable, { type AssignmentRow } from "@/components/rk2/signals/assignmentsTable";
|
||||||
|
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 { formatComponentName } from "@/lib/componentName";
|
||||||
|
import { eaName } from "@/lib/ioEaExport";
|
||||||
|
|
||||||
|
export default async function AssignmentsPage() {
|
||||||
|
const anlage = await api_anlage_getSelected();
|
||||||
|
const [groups, units, signals, ios] = await Promise.all([api_groups(), api_units(), api_signals(), api_ios()]);
|
||||||
|
const groupMap = new Map(groups.map((group) => [group.id, group]));
|
||||||
|
const ioMap = new Map(ios.filter((io) => io.anlageId === anlage.id).map((io) => [io.id, io]));
|
||||||
|
const componentMap = new Map(units.filter((unit) => unit.anlageId === anlage.id).flatMap((unit) =>
|
||||||
|
unit.components.map((component) => [component.id, { unit, component }] as const)));
|
||||||
|
|
||||||
|
const groupPath = (id?: string) => {
|
||||||
|
const names: string[] = [];
|
||||||
|
const seen = new Set<string>();
|
||||||
|
let group = id ? groupMap.get(id) : undefined;
|
||||||
|
while (group && !seen.has(group.id)) {
|
||||||
|
seen.add(group.id);
|
||||||
|
names.unshift(group.name);
|
||||||
|
group = group.parentId ? groupMap.get(group.parentId) : undefined;
|
||||||
|
}
|
||||||
|
return names;
|
||||||
|
};
|
||||||
|
|
||||||
|
const rows: AssignmentRow[] = signals.filter((signal) => signal.anlageId === anlage.id && signal.ioId).map((signal) => {
|
||||||
|
const context = signal.componentId ? componentMap.get(signal.componentId) : undefined;
|
||||||
|
const io = ioMap.get(signal.ioId!);
|
||||||
|
return {
|
||||||
|
id: signal.id,
|
||||||
|
group: context ? groupPath(context.unit.groupId).join('.') || 'Ohne Gruppe' : 'Zuordnung zu Unit fehlt',
|
||||||
|
exportName: context ? eaName(context.unit, context.component, signal.name) : '',
|
||||||
|
variableTable: context ? groupPath(context.unit.groupId)[1] ?? '' : '',
|
||||||
|
exportComment: [context?.unit.bmk, io?.seiteName, io?.functionText].filter(Boolean).join(' '),
|
||||||
|
bmk: context?.unit.bmk ?? '',
|
||||||
|
unit: context?.unit.name ?? 'Nicht verfügbar',
|
||||||
|
unitId: context?.unit.id,
|
||||||
|
component: context ? formatComponentName(context.component) : 'Nicht verfügbar',
|
||||||
|
componentId: context?.component.id,
|
||||||
|
signal: signal.name,
|
||||||
|
type: io?.adrType ?? 'IO nicht verfügbar',
|
||||||
|
byte: io?.adrByte,
|
||||||
|
bit: io?.adrBit,
|
||||||
|
functionText: io?.functionText ?? '',
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return <div className="m-4">
|
||||||
|
<Breadcrumbs items={[{ label: 'Signale', href: '/rk2/signals' }, { label: 'Alle Zuordnungen' }, { label: `${anlage.anlageNr} ${anlage.name}` }]} />
|
||||||
|
<h1 className="my-4 text-xl font-semibold">IO-Zuordnungen ({rows.length})</h1>
|
||||||
|
<Link className="mb-4 inline-block underline" href="/rk2/signals/assignment">Zuordnungen bearbeiten</Link>
|
||||||
|
<AssignmentsTable rows={rows} />
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
@@ -24,6 +24,9 @@ export default async function PageSignale() {
|
|||||||
|
|
||||||
<div className="flex flex-col m-4 w-170 ">
|
<div className="flex flex-col m-4 w-170 ">
|
||||||
<List variant={"default"} size={"lg"} >
|
<List variant={"default"} size={"lg"} >
|
||||||
|
<ListItem hover={true}>
|
||||||
|
<Link href="/rk2/signals/assignments">Alle IO-Zuordnungen</Link>
|
||||||
|
</ListItem>
|
||||||
<ListItem hover={true}>
|
<ListItem hover={true}>
|
||||||
<Link href="/rk2/signals/assignment">IO-Zuordnung</Link>
|
<Link href="/rk2/signals/assignment">IO-Zuordnung</Link>
|
||||||
</ListItem>
|
</ListItem>
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ import { componentDefaults, componentTypeDefinitions } from "@/actions/rk2/api-c
|
|||||||
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
|
import Breadcrumbs from "@/components/ui/navigation/breadcrumbs";
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
|
searchParams: Promise<{ componentId?: string; from?: string }>;
|
||||||
params: Promise<{
|
params: Promise<{
|
||||||
id: string;
|
id: string;
|
||||||
}>;
|
}>;
|
||||||
@@ -18,7 +19,8 @@ type Props = {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
export default async function PageUnitsEdit({ params }: Props) {
|
export default async function PageUnitsEdit({ params, searchParams }: Props) {
|
||||||
|
const { componentId, from } = await searchParams;
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const resultFindUnitById = await api_units_byId(id);
|
const resultFindUnitById = await api_units_byId(id);
|
||||||
@@ -32,13 +34,14 @@ export default async function PageUnitsEdit({ params }: Props) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="">
|
<div className="">
|
||||||
|
{from === 'io-assignment' && <Link className="m-4 inline-block underline" href="/rk2/signals/assignment">Zurück zur IO-Zuordnung</Link>}
|
||||||
<div>
|
<div>
|
||||||
<Breadcrumbs items={breadcrumb}/>
|
<Breadcrumbs items={breadcrumb}/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col m-4 w-300 ">
|
<div className="flex flex-col m-4 w-300 ">
|
||||||
|
|
||||||
<UnitEdit anlage={currentAnlage} groups={groups} selectedUnit={resultFindUnitById.data} componentTypes={componentTypes} componentDefaults={cd}></UnitEdit>
|
<UnitEdit anlage={currentAnlage} groups={groups} selectedUnit={resultFindUnitById.data} componentTypes={componentTypes} componentDefaults={cd} initialComponentId={componentId}></UnitEdit>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { formatComponentName } from "@/lib/componentName";
|
||||||
import { Sites } from "@/_config/sites";
|
import { Sites } from "@/_config/sites";
|
||||||
import { api_units } from "@/actions/rk2/api-units";
|
import { api_units } from "@/actions/rk2/api-units";
|
||||||
import { api_anlage_getSelected } from "@/actions/rk/api-anlage";
|
import { api_anlage_getSelected } from "@/actions/rk/api-anlage";
|
||||||
@@ -56,7 +57,7 @@ export default async function PageUnits() {
|
|||||||
<ListItemDescription className="ps-50 pt-1 flex gap-2">
|
<ListItemDescription className="ps-50 pt-1 flex gap-2">
|
||||||
{unit.components?.map((comp) => <div key={comp.id}>
|
{unit.components?.map((comp) => <div key={comp.id}>
|
||||||
{comp.prefix && comp.prefix}
|
{comp.prefix && comp.prefix}
|
||||||
{comp.name}
|
{formatComponentName(comp)}
|
||||||
{comp.postfix && comp.postfix}
|
{comp.postfix && comp.postfix}
|
||||||
{comp.index && comp.index>0 ? comp.index:""}
|
{comp.index && comp.index>0 ? comp.index:""}
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { formatComponentName } from "@/lib/componentName";
|
||||||
|
|
||||||
import { Anlage } from "@/types/rk";
|
import { Anlage } from "@/types/rk";
|
||||||
import Modal from "@/components/ui/Modal";
|
import Modal from "@/components/ui/Modal";
|
||||||
@@ -39,14 +40,7 @@ export const AusgabeUnitInfo = ({ anlage, groups, units }: Params) => {
|
|||||||
|
|
||||||
//txt += "\t\tKomponenten:"+'\n'
|
//txt += "\t\tKomponenten:"+'\n'
|
||||||
unit.components.forEach((comp)=>{
|
unit.components.forEach((comp)=>{
|
||||||
let cName:string[] = []
|
txt += '\t' + formatComponentName(comp);
|
||||||
comp.prefix && cName.push(comp.prefix);
|
|
||||||
comp.name && cName.push(comp.name + (comp.index ? comp.index.toString():""));
|
|
||||||
//comp.index && cName.push();
|
|
||||||
comp.postfix && cName.push(comp.postfix);
|
|
||||||
//,comp.name,comp.index,comp.postfix
|
|
||||||
|
|
||||||
txt += '\t' + cName.join('_')+''
|
|
||||||
})
|
})
|
||||||
|
|
||||||
return txt;
|
return txt;
|
||||||
|
|||||||
@@ -0,0 +1,118 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { createEaCsv, type EaSource } from "@/lib/ioEaExport";
|
||||||
|
|
||||||
|
export interface AssignmentRow extends EaSource {
|
||||||
|
id: string;
|
||||||
|
group: string;
|
||||||
|
bmk: string;
|
||||||
|
unit: string;
|
||||||
|
unitId?: string;
|
||||||
|
component: string;
|
||||||
|
componentId?: string;
|
||||||
|
signal: string;
|
||||||
|
type: string;
|
||||||
|
byte?: number;
|
||||||
|
bit?: number;
|
||||||
|
functionText: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const columns = [
|
||||||
|
{ key: 'group', label: 'Gruppen' },
|
||||||
|
{ key: 'bmk', label: 'BMK' },
|
||||||
|
{ key: 'unit', label: 'Unit' },
|
||||||
|
{ key: 'component', label: 'Komponente' },
|
||||||
|
{ key: 'signal', label: 'Signal' },
|
||||||
|
{ key: 'type', label: 'Typ' },
|
||||||
|
{ key: 'byte', label: 'Byte' },
|
||||||
|
{ key: 'bit', label: 'Bit' },
|
||||||
|
{ key: 'functionText', label: 'Funktionstext' },
|
||||||
|
] as const;
|
||||||
|
type FilterColumn = Exclude<(typeof columns)[number]['key'], 'bit'>;
|
||||||
|
|
||||||
|
export default function AssignmentsTable({ rows }: { rows: AssignmentRow[] }) {
|
||||||
|
const [filters, setFilters] = useState<Partial<Record<FilterColumn, string>>>({});
|
||||||
|
const [exportError, setExportError] = useState('');
|
||||||
|
const [sort, setSort] = useState<{ column: FilterColumn; descending: boolean }>({ column: 'group', descending: false });
|
||||||
|
const visible = rows.filter((row) => Object.entries(filters).every(([key, filter]) => {
|
||||||
|
const value = row[key as FilterColumn];
|
||||||
|
const terms = filter.trim().toLocaleLowerCase('de').split(/\s+/).filter(Boolean);
|
||||||
|
return terms.every((term) => String(value ?? '').toLocaleLowerCase('de').includes(term));
|
||||||
|
})).sort((a, b) => {
|
||||||
|
const left = a[sort.column], right = b[sort.column];
|
||||||
|
const order = sort.column === 'byte'
|
||||||
|
? left === undefined ? right === undefined ? 0 : 1 : right === undefined ? -1 : Number(left) - Number(right)
|
||||||
|
: String(left ?? '').localeCompare(String(right ?? ''), 'de', { numeric: true, sensitivity: 'base' });
|
||||||
|
return (sort.descending ? -order : order) || a.group.localeCompare(b.group, 'de', { numeric: true })
|
||||||
|
|| a.unit.localeCompare(b.unit, 'de', { numeric: true })
|
||||||
|
|| a.component.localeCompare(b.component, 'de', { numeric: true })
|
||||||
|
|| a.signal.localeCompare(b.signal, 'de', { numeric: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const downloadEaList = () => {
|
||||||
|
setExportError('');
|
||||||
|
try {
|
||||||
|
const csv = createEaCsv(visible);
|
||||||
|
const url = URL.createObjectURL(new Blob([csv], { type: 'text/csv;charset=utf-8' }));
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = 'EA-Liste.csv';
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
} catch (error) {
|
||||||
|
setExportError(error instanceof Error ? error.message : 'Export fehlgeschlagen.');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p className="mb-2">{visible.length} von {rows.length} Zuordnungen</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="mb-4 rounded border px-3 py-2 disabled:opacity-50"
|
||||||
|
disabled={visible.length === 0}
|
||||||
|
onClick={downloadEaList}>EA-Liste exportieren (CSV)
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{exportError && <p role="alert" className="mb-4 text-red-600">{exportError}</p>}
|
||||||
|
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full border-collapse text-left text-sm">
|
||||||
|
<thead>
|
||||||
|
<tr>{columns.map(({ key, label }) => (
|
||||||
|
<th key={key} className="border p-2" aria-sort={key === sort.column ? sort.descending ? 'descending' : 'ascending' : undefined}>
|
||||||
|
{key === 'bit' ? label : <button type="button" className="font-semibold" onClick={() => setSort((current) => ({
|
||||||
|
column: key, descending: current.column === key ? !current.descending : false,
|
||||||
|
}))}>{label} {key === sort.column ? sort.descending ? '▼' : '▲' : '↕'}</button>}
|
||||||
|
</th>))}
|
||||||
|
</tr>
|
||||||
|
<tr>{columns.map(({ key, label }) => <th key={key} className="border p-2">
|
||||||
|
{key !== 'bit' && <input type="search" aria-label={`${label} filtern`} placeholder={`${label} filtern`}
|
||||||
|
className="w-full min-w-24 rounded border p-1 font-normal" value={filters[key] ?? ''}
|
||||||
|
onChange={(event) => setFilters((current) => ({ ...current, [key]: event.target.value }))} />}
|
||||||
|
</th>)}</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>{visible.map((row) => (
|
||||||
|
<tr key={row.id}>
|
||||||
|
<td className="border p-2">{row.group}</td>
|
||||||
|
<td className="border p-2">{row.bmk || '–'}</td>
|
||||||
|
<td className="border p-2">{row.unitId ? <Link className="underline" href={`/rk2/units/edit/${encodeURIComponent(row.unitId)}`}>{row.unit}</Link> : row.unit}</td>
|
||||||
|
<td className="border p-2">{row.componentId ? <Link className="underline" href={`/rk2/signals/${encodeURIComponent(row.componentId)}`}>{row.component}</Link> : row.component}</td>
|
||||||
|
<td className="border p-2">{row.signal}</td>
|
||||||
|
<td className="border p-2">{row.type}</td>
|
||||||
|
<td className="border p-2">{row.byte ?? '–'}</td>
|
||||||
|
<td className="border p-2">{row.bit ?? '–'}</td>
|
||||||
|
<td className="border p-2">{row.functionText || '–'}</td>
|
||||||
|
</tr>)
|
||||||
|
)}
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
|
||||||
|
{visible.length === 0 && <p className="mt-4">Keine Zuordnungen passend zum Filter.</p>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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<string>();
|
||||||
|
const [deleting, setDeleting] = useState<string>();
|
||||||
|
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 <section>
|
||||||
|
<h2 className="mb-2 font-semibold">Vorhandene Signale ({signals.length})</h2>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
{message && <p role="status">{message}</p>}
|
||||||
|
<div className="mb-6 overflow-x-auto"><table className="w-full border-collapse text-left">
|
||||||
|
<thead><tr>{['Name', 'Typ', 'Beschreibung', 'IO', 'Aktionen'].map((label) => <th key={label} className="border p-2">{label}</th>)}</tr></thead>
|
||||||
|
<tbody>{signals.map((signal) => {
|
||||||
|
const io = ios.find((item) => item.id === signal.ioId && item.anlageId === anlageId);
|
||||||
|
return <tr key={signal.id}>
|
||||||
|
<td className="border p-2">{signal.name}</td>
|
||||||
|
<td className="border p-2">{signal.type}</td>
|
||||||
|
<td className="border p-2">{signal.description}</td>
|
||||||
|
<td className="border p-2">{io ? `${io.adrType} ${io.adrByte}${io.adrBit == null ? '' : `.${io.adrBit}`} – ${io.functionText ?? ''}` : signal.ioId ? 'IO nicht verfügbar' : 'Nicht zugeordnet'}</td>
|
||||||
|
<td className="border p-2"><div className="flex flex-wrap gap-2">
|
||||||
|
<Button type="button" size="sm" disabled={busy} onClick={() => { setEditing(signal.id); setDeleting(undefined); setError(''); }}>Bearbeiten</Button>
|
||||||
|
<Button type="button" size="sm" variant="danger" disabled={busy} onClick={() => { setDeleting(signal.id); setEditing(undefined); setError(''); }}>Löschen</Button>
|
||||||
|
</div>
|
||||||
|
{deleting === signal.id && <div className="mt-2">
|
||||||
|
<p>Signal „{signal.name}“ löschen? Der IO bleibt erhalten.</p>
|
||||||
|
<Button type="button" variant="danger" size="sm" disabled={busy} onClick={() => remove(signal.id)}>Löschen bestätigen</Button>
|
||||||
|
<Button type="button" variant="secondary" size="sm" disabled={busy} onClick={() => setDeleting(undefined)}>Abbrechen</Button>
|
||||||
|
</div>}</td>
|
||||||
|
</tr>;
|
||||||
|
})}</tbody>
|
||||||
|
</table>{signals.length === 0 && <p>Noch keine Signale angelegt.</p>}</div>
|
||||||
|
{editing && signals.find((item) => item.id === editing) && <div>
|
||||||
|
<h2 className="mb-2 font-semibold">Signal bearbeiten</h2>
|
||||||
|
<SignalForm key={editing} componente={component} initSignal={signals.find((item) => item.id === editing)} onSaved={() => setEditing(undefined)} />
|
||||||
|
<Button type="button" variant="secondary" onClick={() => setEditing(undefined)}>Bearbeitung schließen</Button>
|
||||||
|
</div>}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client"
|
"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 { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
@@ -8,16 +8,22 @@ import { Select } from "@/components/ui/select";
|
|||||||
import { useSignal } from "@/hooks/rk2/useSignal";
|
import { useSignal } from "@/hooks/rk2/useSignal";
|
||||||
import { ComponentResponse } from "@/types/anlagen/components"
|
import { ComponentResponse } from "@/types/anlagen/components"
|
||||||
import { SignalCreate, SignalResponse, SignalType } from "@/types/anlagen/signals"
|
import { SignalCreate, SignalResponse, SignalType } from "@/types/anlagen/signals"
|
||||||
import { useEffect } from "react";
|
import { useEffect, useState } from "react";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
componente: ComponentResponse,
|
componente: ComponentResponse,
|
||||||
initSignal?: SignalResponse,
|
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({});
|
const { setSignal, setValue, signalData, string_to_signalType } = useSignal({});
|
||||||
|
|
||||||
@@ -27,34 +33,53 @@ export function SignalForm({ componente, initSignal }: Props) {
|
|||||||
}, [initSignal]);
|
}, [initSignal]);
|
||||||
*/
|
*/
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
if (initSignal) setSignal({ ...initSignal, componentId: componente.id });
|
||||||
setValue("componentId",componente.id);
|
setValue("componentId",componente.id);
|
||||||
//if (initSignal) setSignal({...initSignal,componentId:componente.id});
|
//if (initSignal) setSignal({...initSignal,componentId:componente.id});
|
||||||
// setSignal({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")
|
console.log("save")
|
||||||
const saveData:SignalCreate ={
|
const saveData:SignalCreate ={
|
||||||
componentId:signalData.componentId!,
|
componentId:componente.id,
|
||||||
name:signalData.name!,
|
name:signalData.name.trim(),
|
||||||
description:signalData.description!,
|
description:signalData.description!,
|
||||||
type:signalData.type!,
|
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 (
|
return (
|
||||||
<div style={{ border: "1px solid #ccc", padding: 16, marginBottom: 16, borderRadius: 8, }} >
|
<div style={{ border: "1px solid #ccc", padding: 16, marginBottom: 16, borderRadius: 8, }} >
|
||||||
|
|
||||||
{/*---Form Data */}
|
{/*---Form Data */}
|
||||||
<div className="flex gap-4">
|
<fieldset disabled={saving} className="flex flex-wrap gap-4">
|
||||||
<div className="w-30 flex flex-row">
|
<div className="w-30 flex flex-row">
|
||||||
<Label size={"xs"} >Name</Label>
|
<Label size={"xs"} >Name</Label>
|
||||||
<Input sizeVariant={"xs"} type="text" value={signalData.name} onChange={(e) => setValue('name', e.target.value)} />
|
<Input sizeVariant={"xs"} type="text" value={signalData.name ?? ''} onChange={(e) => setValue('name', e.target.value)} />
|
||||||
</div>
|
</div>
|
||||||
<div className="w-50 flex flex-row">
|
<div className="w-50 flex flex-row">
|
||||||
<Label className="w-30" size={"xs"} >Signal Typ</Label>
|
<Label className="w-30" size={"xs"} >Signal Typ</Label>
|
||||||
<Select sizeVariant={"xs"} value={signalData.type} onChange={(e) => setValue('type', string_to_signalType(e.target.value))} >
|
<Select sizeVariant={"xs"} value={signalData.type ?? SignalType.DIGITAL_INPUT} onChange={(e) => setValue('type', string_to_signalType(e.target.value))} >
|
||||||
<option value={SignalType.ANALOG_INPUT}>{SignalType.ANALOG_INPUT}</option>
|
<option value={SignalType.ANALOG_INPUT}>{SignalType.ANALOG_INPUT}</option>
|
||||||
<option value={SignalType.ANALOG_OUTPUT}>{SignalType.ANALOG_OUTPUT}</option>
|
<option value={SignalType.ANALOG_OUTPUT}>{SignalType.ANALOG_OUTPUT}</option>
|
||||||
<option value={SignalType.DIGITAL_INPUT}>{SignalType.DIGITAL_INPUT}</option>
|
<option value={SignalType.DIGITAL_INPUT}>{SignalType.DIGITAL_INPUT}</option>
|
||||||
@@ -63,19 +88,21 @@ export function SignalForm({ componente, initSignal }: Props) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="w-40 flex flex-row">
|
<div className="w-40 flex flex-row">
|
||||||
<Label size={"xs"} >Beschreibung</Label>
|
<Label size={"xs"} >Beschreibung</Label>
|
||||||
<Input sizeVariant={"xs"} type="text" value={signalData.description} onChange={(e) => setValue('description', e.target.value)} />
|
<Input sizeVariant={"xs"} type="text" value={signalData.description ?? ''} onChange={(e) => setValue('description', e.target.value)} />
|
||||||
</div>
|
|
||||||
<Button onClick={()=>handlerSave()} >Save </Button>
|
|
||||||
</div>
|
</div>
|
||||||
|
<Button type="button" disabled={saving} onClick={()=>handlerSave()}>{saving ? 'Wird gespeichert…' : initSignal ? 'Änderungen speichern' : 'Signal anlegen'}</Button>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
|
||||||
{true &&
|
{false &&
|
||||||
<div>
|
<div>
|
||||||
<pre>{JSON.stringify(signalData, null, 2)}</pre>
|
<pre>{JSON.stringify(signalData, null, 2)}</pre>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
}
|
}
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
{message && <p role="status">{message}</p>}
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
"use client";
|
"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 { api_signals_assignIos, api_signals } from "@/actions/rk2/api-signals";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import IoFilter from "@/components/rk2/ios/ioFilter";
|
import IoFilter from "@/components/rk2/ios/ioFilter";
|
||||||
@@ -15,6 +19,7 @@ interface Props {
|
|||||||
signals: SignalResponse[];
|
signals: SignalResponse[];
|
||||||
ios: IoResponse[];
|
ios: IoResponse[];
|
||||||
anlageId: string;
|
anlageId: string;
|
||||||
|
initialUnitId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function ioLabel(io: IoResponse) {
|
function ioLabel(io: IoResponse) {
|
||||||
@@ -34,27 +39,64 @@ function groupPath(id: string | undefined, groups: GroupResponse[]): string {
|
|||||||
return parts.join(' / ') || 'Unbekannte Gruppe';
|
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 [signals, setSignals] = useState(initialSignals);
|
||||||
const [pending, setPending] = useState<Record<string, string | null>>({});
|
const router = useRouter();
|
||||||
const effectiveSignals = signals.map((item) => Object.hasOwn(pending, item.id) ? { ...item, ioId: pending[item.id] ?? undefined } : item);
|
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 = <K extends keyof AssignmentSettings>(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 pendingCount = Object.keys(pending).length;
|
||||||
|
const unitsRef = useRef<HTMLDivElement>(null), signalsRef = useRef<HTMLDivElement>(null);
|
||||||
|
const iosRef = useRef<HTMLDivElement>(null), pendingRef = useRef<HTMLDivElement>(null);
|
||||||
|
const restored = useRef(false);
|
||||||
|
const previousSelection = useRef('');
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!pendingCount) return;
|
if (!ready || restored.current) return;
|
||||||
const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = ''; };
|
const selectedUnit = units.find((item) => item.id === (initialUnitId ?? settings.unitId));
|
||||||
window.addEventListener('beforeunload', warn);
|
const restoredSignalId = initialUnitId && initialUnitId !== settings.unitId
|
||||||
return () => window.removeEventListener('beforeunload', warn);
|
? signals.find((item) => !item.ioId && selectedUnit?.components.some((component) => component.id === item.componentId))?.id
|
||||||
}, [pendingCount]);
|
: settings.signalId;
|
||||||
const [unitId, setUnitId] = useState('');
|
const selectedSignal = signals.find((item) => item.id === restoredSignalId && item.anlageId === anlageId
|
||||||
const [signalId, setSignalId] = useState('');
|
&& 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(() => {
|
useEffect(() => {
|
||||||
|
if (!restored.current || previousSelection.current === signalId) return;
|
||||||
|
previousSelection.current = signalId;
|
||||||
document.getElementById(`assignment-signal-${signalId}`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
document.getElementById(`assignment-signal-${signalId}`)?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||||
}, [signalId]);
|
}, [signalId]);
|
||||||
const [ioId, setIoId] = useState('');
|
const snapshot = (): AssignmentSettings => ({ ...settings, scroll: {
|
||||||
const [functionText, setFunctionText] = useState('');
|
units: unitsRef.current?.scrollTop ?? 0, signals: signalsRef.current?.scrollTop ?? 0,
|
||||||
const [adrByte, setAdrByte] = useState('');
|
ios: iosRef.current?.scrollTop ?? 0, pending: pendingRef.current?.scrollTop ?? 0,
|
||||||
const [hideAssigned, setHideAssigned] = useState(false);
|
} });
|
||||||
const [hideUsedIos, setHideUsedIos] = useState(false);
|
const openUnit = () => {
|
||||||
|
if (!unitId || !persist(snapshot())) return;
|
||||||
|
router.push(`/rk2/units/edit/${encodeURIComponent(unitId)}?from=io-assignment`);
|
||||||
|
};
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
const [message, setMessage] = useState('');
|
const [message, setMessage] = useState('');
|
||||||
const [error, setError] = useState('');
|
const [error, setError] = useState('');
|
||||||
@@ -65,7 +107,7 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
const owners = new Map<string, SignalResponse[]>();
|
const owners = new Map<string, SignalResponse[]>();
|
||||||
for (const item of effectiveSignals) if (item.ioId) owners.set(item.ioId, [...(owners.get(item.ioId) ?? []), item]);
|
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 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 textFilter = functionText.trim().toLocaleLowerCase('de');
|
||||||
const textTerms = textFilter.split(/\s+/).filter(Boolean);
|
const textTerms = textFilter.split(/\s+/).filter(Boolean);
|
||||||
const byteFilter = adrByte.trim();
|
const byteFilter = adrByte.trim();
|
||||||
@@ -74,7 +116,13 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
&& ((!textFilter && !byteFilter)
|
&& ((!textFilter && !byteFilter)
|
||||||
|| (textTerms.length > 0 && textTerms.every((term) => (io.functionText ?? '').toLocaleLowerCase('de').includes(term)))
|
|| (textTerms.length > 0 && textTerms.every((term) => (io.functionText ?? '').toLocaleLowerCase('de').includes(term)))
|
||||||
|| (byteFilter !== '' && io.adrByte === Number(byteFilter))))
|
|| (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<string, UnitResponse[]>();
|
const unitGroups = new Map<string, UnitResponse[]>();
|
||||||
for (const item of [...units].sort((a, b) => a.name.localeCompare(b.name, 'de', { numeric: true }))) {
|
for (const item of [...units].sort((a, b) => a.name.localeCompare(b.name, 'de', { numeric: true }))) {
|
||||||
const key = item.groupId ?? '';
|
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;
|
if (targetIoId && (owners.get(targetIoId) ?? []).some((owner) => owner.id !== signal.id)) return;
|
||||||
setPending((items) => {
|
setPending((items) => {
|
||||||
const updated = { ...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];
|
if (original === targetIoId) delete updated[signal.id];
|
||||||
else updated[signal.id] = targetIoId;
|
else updated[signal.id] = { ioId: targetIoId, previousIoId: original };
|
||||||
return updated;
|
return updated;
|
||||||
});
|
});
|
||||||
setMessage(`Zuordnung für ${signal.name} vorgemerkt.`);
|
setMessage(`Zuordnung für ${signal.name} vorgemerkt.`);
|
||||||
@@ -134,7 +182,7 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
setMessage('');
|
setMessage('');
|
||||||
try {
|
try {
|
||||||
const result = await api_signals_assignIos(Object.entries(pending).map(([id, target]) => ({
|
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; }
|
if (!result.success) { setError(result.errors.join(', ')); return; }
|
||||||
const saved = new Map(result.data.map((item) => [item.id, item]));
|
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); }
|
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 <p role="status">Einstellungen werden geladen…</p>;
|
||||||
return <div className="mt-4">
|
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="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 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-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="mb-3">IO: <strong>{selectedIo ? ioLabel(selectedIo) : 'Bitte auswählen'}</strong></div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<Button type="button" disabled={busy || !pendingCount} onClick={saveAll}>
|
<Button type="button" disabled={busy || !pendingCount || conflicts.length > 0} onClick={saveAll}>
|
||||||
{busy ? 'Wird gespeichert…' : 'Alle speichern'}
|
{busy ? 'Wird gespeichert…' : 'Alle speichern'}
|
||||||
</Button>
|
</Button>
|
||||||
<Button type="button" variant="secondary" disabled={busy || !signal?.ioId} onClick={() => stage(null)}>Zuordnung entfernen</Button>
|
<Button type="button" variant="secondary" disabled={busy || !signal?.ioId} onClick={() => stage(null)}>Zuordnung entfernen</Button>
|
||||||
@@ -169,15 +223,18 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
const target = orderedUnits[orderedUnits.findIndex((item) => item.id === unitId) + 1];
|
const target = orderedUnits[orderedUnits.findIndex((item) => item.id === unitId) + 1];
|
||||||
if (target) chooseUnit(target);
|
if (target) chooseUnit(target);
|
||||||
}}>Nächste Unit</Button>
|
}}>Nächste Unit</Button>
|
||||||
|
{unit && <Button type="button" variant="secondary" disabled={busy} onClick={openUnit}>Unit öffnen: {unit.name}</Button>}
|
||||||
</div>
|
</div>
|
||||||
{occupied && <p className="mt-2">Dieser IO ist bereits einem anderen Signal zugeordnet.</p>}
|
{occupied && <p className="mt-2">Dieser IO ist bereits einem anderen Signal zugeordnet.</p>}
|
||||||
|
{storageError && <p role="alert">{storageError}</p>}
|
||||||
|
{conflicts.length > 0 && <p role="alert">{conflicts.length} Vormerkungen betreffen gelöschte oder geänderte Daten. Bitte prüfen oder zurücknehmen.</p>}
|
||||||
{error && <p role="alert" className="mt-2">{error}</p>}
|
{error && <p role="alert" className="mt-2">{error}</p>}
|
||||||
{message && <p role="status" className="mt-2">{message}</p>}
|
{message && <p role="status" className="mt-2">{message}</p>}
|
||||||
</div>
|
</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)]">
|
<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">
|
<section className="min-w-0 rounded border p-3">
|
||||||
<h2 className="mb-3 font-semibold">Units nach Gruppe</h2>
|
<h2 className="mb-3 font-semibold">Units nach Gruppe</h2>
|
||||||
<div className="max-h-[65vh] overflow-y-auto">
|
<div ref={unitsRef} className="max-h-[65vh] overflow-y-auto" onScroll={(event) => { const top = event.currentTarget.scrollTop; if (restored.current) setSettings((s) => ({ ...s, scroll: { ...s.scroll, units: top } })); }}>
|
||||||
{sortedGroups.map(([id, items]) => <div key={id} className="mb-4">
|
{sortedGroups.map(([id, items]) => <div key={id} className="mb-4">
|
||||||
<h3 className="mb-2 text-sm font-semibold">{groupPath(id, groups)}</h3>
|
<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}
|
{items.map((item) => <button type="button" key={item.id} disabled={busy} aria-pressed={unitId === item.id}
|
||||||
@@ -199,7 +256,7 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
Zugeordnete Signale ausblenden
|
Zugeordnete Signale ausblenden
|
||||||
</label>
|
</label>
|
||||||
{!unit && <p>Unit auswählen, dann ein IO anklicken. Das nächste freie Signal wird automatisch ausgewählt.</p>}
|
{!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) => {
|
<div ref={signalsRef} onScroll={(event) => { const top = event.currentTarget.scrollTop; if (restored.current) setSettings((s) => ({ ...s, scroll: { ...s.scroll, signals: top } })); }} className="max-h-[65vh] overflow-y-auto" onKeyDown={(event) => {
|
||||||
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
|
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const items = unitSignals(unit);
|
const items = unitSignals(unit);
|
||||||
@@ -210,7 +267,8 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
{unit?.components.map((component) => {
|
{unit?.components.map((component) => {
|
||||||
const items = effectiveSignals.filter((item) => item.anlageId === anlageId && item.componentId === component.id && !Object.hasOwn(pending, item.id) && (!hideAssigned || !item.ioId));
|
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">
|
return <div key={component.id} className="mb-4">
|
||||||
<h3 className="mb-2 text-sm font-semibold">{component.name}</h3>
|
<h3 className="mb-2 text-sm font-semibold">{formatComponentName(component)}</h3>
|
||||||
|
{pendingCount === 0 && <Link className="mb-2 inline-block text-sm underline" href={`/rk2/signals/${encodeURIComponent(component.id)}`}>Signale verwalten</Link>}
|
||||||
{items.map((item) => {
|
{items.map((item) => {
|
||||||
const current = ios.find((io) => io.id === item.ioId);
|
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}
|
return <button id={`assignment-signal-${item.id}`} key={item.id} type="button" disabled={busy} aria-pressed={signalId === item.id}
|
||||||
@@ -237,7 +295,13 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
Benutzte IOs ausblenden
|
Benutzte IOs ausblenden
|
||||||
</label>
|
</label>
|
||||||
<IoFilter functionText={functionText} adrByte={adrByte} onFunctionTextChange={setFunctionText} onAdrByteChange={setAdrByte} />
|
<IoFilter functionText={functionText} adrByte={adrByte} onFunctionTextChange={setFunctionText} onAdrByteChange={setAdrByte} />
|
||||||
<div className="max-h-[55vh] overflow-y-auto">
|
<label className="mb-3 flex items-center gap-2">Sortierung
|
||||||
|
<select className="rounded border p-2" value={ioSort} onChange={(event) => setIoSort(event.target.value === 'address' ? 'address' : 'functionText')}>
|
||||||
|
<option value="functionText">Funktionstext</option>
|
||||||
|
<option value="address">Adresse: Typ, Byte, Bit</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<div ref={iosRef} onScroll={(event) => { const top = event.currentTarget.scrollTop; if (restored.current) setSettings((s) => ({ ...s, scroll: { ...s.scroll, ios: top } })); }} className="max-h-[55vh] overflow-y-auto">
|
||||||
{visibleIos.map((io) => {
|
{visibleIos.map((io) => {
|
||||||
const ownerList = owners.get(io.id) ?? [];
|
const ownerList = owners.get(io.id) ?? [];
|
||||||
const taken = ownerList.some((item) => item.id !== signalId);
|
const taken = ownerList.some((item) => item.id !== signalId);
|
||||||
@@ -254,15 +318,16 @@ export default function SignalIoAssignment({ groups, units, signals: initialSign
|
|||||||
</section>
|
</section>
|
||||||
<section className="min-w-0 rounded border bg-white p-3 text-gray-900">
|
<section className="min-w-0 rounded border bg-white p-3 text-gray-900">
|
||||||
<h2 className="mb-3 font-semibold">Vormerkungen ({pendingCount})</h2>
|
<h2 className="mb-3 font-semibold">Vormerkungen ({pendingCount})</h2>
|
||||||
{pendingCount > 0 && <div className="max-h-[65vh] overflow-y-auto">
|
{pendingCount > 0 && <div ref={pendingRef} onScroll={(event) => { 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, targetIoId]) => {
|
{Object.entries(pending).map(([id, assignment]) => {
|
||||||
|
const targetIoId = assignment.ioId;
|
||||||
const item = signals.find((signal) => signal.id === id);
|
const item = signals.find((signal) => signal.id === id);
|
||||||
const targetIo = ios.find((io) => io.id === targetIoId);
|
const targetIo = ios.find((io) => io.id === targetIoId);
|
||||||
const targetUnit = units.find((unit) => unit.components.some((component) => component.id === item?.componentId));
|
const targetUnit = units.find((unit) => unit.components.some((component) => component.id === item?.componentId));
|
||||||
const component = targetUnit?.components.find((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">
|
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>
|
||||||
<div className="text-sm">{targetUnit?.name} / {component?.name}</div>
|
<div className="text-sm">{targetUnit?.name} / {component ? formatComponentName(component) : ''}</div>
|
||||||
<div><strong>{item?.name ?? id}</strong> → {targetIoId === null ? 'Zuordnung entfernen' : targetIo ? ioLabel(targetIo) : targetIoId}</div>
|
<div><strong>{item?.name ?? id}</strong> → {targetIoId === null ? 'Zuordnung entfernen' : targetIo ? ioLabel(targetIo) : targetIoId}</div>
|
||||||
</div>
|
</div>
|
||||||
<Button type="button" variant="secondary" size="sm" disabled={busy} onClick={() => removePending(id)}>Vormerkung löschen</Button>
|
<Button type="button" variant="secondary" size="sm" disabled={busy} onClick={() => removePending(id)}>Vormerkung löschen</Button>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"use client"
|
"use client"
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
import { PropertyField } from "./propertyFields"
|
import { PropertyField } from "./propertyFields"
|
||||||
import { ComponentDefaults, ComponentResponse, ComponentType, ComponentTypeDefinition } from "@/types/anlagen/components"
|
import { ComponentDefaults, ComponentResponse, ComponentType, ComponentTypeDefinition } from "@/types/anlagen/components"
|
||||||
@@ -112,6 +113,7 @@ export function ComponentForm({ component, componentTypes, componentDefaults, on
|
|||||||
|
|
||||||
|
|
||||||
{/* --- Signal IDs ----*/}
|
{/* --- Signal IDs ----*/}
|
||||||
|
<Link href={`/rk2/signals/${encodeURIComponent(component.id)}`} className="inline-block my-3 underline">Signale verwalten</Link>
|
||||||
{signalByComp && signalByComp.map((s) => <div key={s.id}>
|
{signalByComp && signalByComp.map((s) => <div key={s.id}>
|
||||||
{s.name}
|
{s.name}
|
||||||
</div>)}
|
</div>)}
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import { ComponentDefaults, ComponentTypeDefinition } from "@/types/anlagen/comp
|
|||||||
|
|
||||||
|
|
||||||
interface Params {
|
interface Params {
|
||||||
|
initialComponentId?: string;
|
||||||
anlage: Anlage,
|
anlage: Anlage,
|
||||||
groups: GroupResponse[],
|
groups: GroupResponse[],
|
||||||
selectedUnit?: UnitResponse,
|
selectedUnit?: UnitResponse,
|
||||||
@@ -22,7 +23,7 @@ interface Params {
|
|||||||
componentDefaults: ComponentDefaults[]
|
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 });
|
const { getGroupById } = useGroups({ groups });
|
||||||
@@ -55,7 +56,7 @@ export const UnitEdit = ({ anlage, groups, selectedUnit, componentTypes,componen
|
|||||||
return (
|
return (
|
||||||
<div className="" >
|
<div className="" >
|
||||||
|
|
||||||
<UnitCreateForm anlage={anlage} selectedGroup={selectedGroup} onDisplaySelectGroup={() => setShowSelectGroup(true)} unitIntial={selectedUnit} componentTypes={componentTypes} componentDefaults={componentDefaults}/>
|
<UnitCreateForm anlage={anlage} selectedGroup={selectedGroup} onDisplaySelectGroup={() => setShowSelectGroup(true)} unitIntial={selectedUnit} componentTypes={componentTypes} componentDefaults={componentDefaults} initialComponentId={initialComponentId}/>
|
||||||
|
|
||||||
{showSelectGroup &&
|
{showSelectGroup &&
|
||||||
<Modal onClose={() => setShowSelectGroup(false)} >
|
<Modal onClose={() => setShowSelectGroup(false)} >
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
import { formatComponentName } from "@/lib/componentName";
|
||||||
|
|
||||||
import { useEffect, useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
import { Anlage } from "@/types/rk";
|
import { Anlage } from "@/types/rk";
|
||||||
@@ -21,6 +22,7 @@ import { Select } from "@/components/ui/select";
|
|||||||
|
|
||||||
|
|
||||||
interface Params {
|
interface Params {
|
||||||
|
initialComponentId?: string;
|
||||||
anlage: Anlage,
|
anlage: Anlage,
|
||||||
unitIntial?: UnitResponse
|
unitIntial?: UnitResponse
|
||||||
selectedGroup?: GroupResponse
|
selectedGroup?: GroupResponse
|
||||||
@@ -30,9 +32,9 @@ interface Params {
|
|||||||
debug?: boolean
|
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<string>();
|
const [id, setId] = useState<string>();
|
||||||
const [selectedComponent, setSelectedComponent] = useState<ComponentResponse>();
|
const [selectedComponent, setSelectedComponent] = useState<ComponentResponse | undefined>(() => unitIntial?.components.find((component) => component.id === initialComponentId));
|
||||||
|
|
||||||
|
|
||||||
const { emptyUnit, unitType, setValue, unitData, string_to_UnitType } = useUnit({ unit: unitIntial });
|
const { emptyUnit, unitType, setValue, unitData, string_to_UnitType } = useUnit({ unit: unitIntial });
|
||||||
@@ -163,7 +165,7 @@ export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selec
|
|||||||
<List variant="transparent" border={"none"} divide={false} size={"sm"}>
|
<List variant="transparent" border={"none"} divide={false} size={"sm"}>
|
||||||
{componentNames.map((comp) => (
|
{componentNames.map((comp) => (
|
||||||
<ListItem className="" key={comp.id}>
|
<ListItem className="" key={comp.id}>
|
||||||
<Button onClick={() => handlerAppendComponent(comp.id)} type="button" key={comp.id} variant={"select"} size={"xs"} >{comp.name}</Button>
|
<Button onClick={() => handlerAppendComponent(comp.id)} type="button" key={comp.id} variant={"select"} size={"xs"} >{formatComponentName(comp)}</Button>
|
||||||
</ListItem>
|
</ListItem>
|
||||||
))}
|
))}
|
||||||
</List>
|
</List>
|
||||||
@@ -189,10 +191,7 @@ export const UnitCreateForm = ({ anlage, unitIntial, onDisplaySelectGroup, selec
|
|||||||
</ListItemTitle>
|
</ListItemTitle>
|
||||||
|
|
||||||
<ListItemDescription>
|
<ListItemDescription>
|
||||||
{c.prefix && c.prefix}
|
{formatComponentName(c)}
|
||||||
{c.name}
|
|
||||||
{c.postfix && c.postfix}
|
|
||||||
{c.index && c.index > 0 ? c.index: ""}
|
|
||||||
</ListItemDescription>
|
</ListItemDescription>
|
||||||
</ListItemContent>
|
</ListItemContent>
|
||||||
|
|
||||||
|
|||||||
@@ -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<string, PendingAssignment>;
|
||||||
|
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<string, unknown>;
|
||||||
|
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<string, unknown>;
|
||||||
|
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<string, unknown>;
|
||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -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 ?? ''}`;
|
||||||
|
}
|
||||||
@@ -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<string, string> = {
|
||||||
|
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<string>();
|
||||||
|
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');
|
||||||
|
}
|
||||||
Reference in new issue
Block a user