unit template

This commit is contained in:
marco committed 2026-10-12 16:42:07 +02:00
1 parent c15e69f7b5
commit 3bea468d23
11 files changed
+391 -4

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
"use client";
import { useMemo, useState } from "react";
import Link from "next/link";
import IoFilter from "@/components/rk2/ios/ioFilter";
import { Button } from "@/components/ui/button";
import { formatComponentName } from "@/lib/componentName";
import type { IoResponse } from "@/types/anlagen/ios";
import type { SignalResponse } from "@/types/anlagen/signals";
import type { UnitResponse } from "@/types/anlagen/units";
interface Props { ios: IoResponse[]; signals: SignalResponse[]; units: UnitResponse[] }
export default function IoOverview({ ios, signals, units }: Props) {
const [functionText, setFunctionText] = useState('');
const [adrByte, setAdrByte] = useState('');
const [type, setType] = useState('');
const [assignment, setAssignment] = useState('');
const [signalText, setSignalText] = useState('');
const owners = useMemo(() => {
const map = new Map<string, SignalResponse[]>();
for (const signal of signals) if (signal.ioId) {
const entries = map.get(signal.ioId) ?? [];
entries.push(signal);
map.set(signal.ioId, entries);
}
return map;
}, [signals]);
const contexts = useMemo(() => new Map(units.flatMap((unit) =>
unit.components.map((component) => [component.id, { unit, component }] as const))), [units]);
const terms = functionText.trim().toLocaleLowerCase('de').split(/\s+/).filter(Boolean);
const signalTerms = signalText.trim().toLocaleLowerCase('de').split(/\s+/).filter(Boolean);
const visible = ios.filter((io) => {
const linked = owners.get(io.id) ?? [];
return (!type || io.adrType === type)
&& (!assignment || (assignment === 'free' ? linked.length === 0 : assignment === 'multiple' ? linked.length > 1 : linked.length > 0))
&& ((!terms.length && !adrByte.trim())
|| (terms.length > 0 && terms.every((term) => (io.functionText ?? '').toLocaleLowerCase('de').includes(term)))
|| (adrByte.trim() !== '' && io.adrByte === Number(adrByte)))
&& (!signalTerms.length || linked.some((signal) => {
const context = signal.componentId ? contexts.get(signal.componentId) : undefined;
const text = [signal.name, signal.description, context?.unit.name, context?.unit.bmk,
context ? formatComponentName(context.component) : ''].join(' ').toLocaleLowerCase('de');
return signalTerms.every((term) => text.includes(term));
}));
}).sort((a, b) => a.adrType.localeCompare(b.adrType, 'de') || a.adrByte - b.adrByte || (a.adrBit ?? -1) - (b.adrBit ?? -1));
return <>
<div className="mb-4 grid gap-4 rounded border p-4 md:grid-cols-2">
<IoFilter functionText={functionText} adrByte={adrByte} onFunctionTextChange={setFunctionText} onAdrByteChange={setAdrByte} />
<div className="grid gap-2">
<label>Adresstyp
<select className="mt-1 w-full rounded border p-2" value={type} onChange={(event) => setType(event.target.value)}>
<option value="">Alle Typen</option>
{[...new Set(ios.map((io) => io.adrType))].sort().map((value) => <option key={value} value={value}>{value}</option>)}
</select>
</label>
<label>Signal-Verknüpfung
<select className="mt-1 w-full rounded border p-2" value={assignment} onChange={(event) => setAssignment(event.target.value)}>
<option value="">Alle IOs</option>
<option value="assigned">Mit Signal</option>
<option value="free">Ohne Signal</option>
<option value="multiple">Mehrfach verknüpft</option>
</select>
</label>
<label>Signal, Unit, BMK oder Komponente
<input type="search" className="mt-1 w-full rounded border p-2" value={signalText}
onChange={(event) => setSignalText(event.target.value)} placeholder="Verknüpfungen durchsuchen" />
</label>
</div>
<Button type="button" variant="secondary" onClick={() => {
setFunctionText(''); setAdrByte(''); setType(''); setAssignment(''); setSignalText('');
}}>Filter zurücksetzen</Button>
</div>
<p className="mb-3 text-sm" aria-live="polite">{visible.length} von {ios.length} IOs · {ios.filter((io) => owners.has(io.id)).length} mit Signal</p>
<div className="overflow-x-auto rounded border">
<table className="w-full text-left text-sm">
<thead className="bg-gray-100"><tr>
{['Adresse', 'Funktionstext', 'Seite', 'Signal-Verknüpfungen'].map((title) => <th key={title} scope="col" className="p-3">{title}</th>)}
</tr></thead>
<tbody>{visible.map((io) => <tr key={io.id} className="border-t align-top">
<td className="whitespace-nowrap p-3 font-mono">{io.adrType} {io.adrByte}{io.adrBit == null ? '' : `.${io.adrBit}`}</td>
<td className="p-3">{io.functionText || '—'}</td>
<td className="p-3">{[io.seite, io.seiteName].filter((value) => value !== undefined && value !== '').join(' · ') || '—'}</td>
<td className="p-3">{(owners.get(io.id) ?? []).length === 0 ? <span className="text-gray-500">Ohne Signal</span>
: (owners.get(io.id) ?? []).map((signal) => {
const context = signal.componentId ? contexts.get(signal.componentId) : undefined;
return <div key={signal.id} className="mb-2 last:mb-0">
{context ? <Link className="underline" href={`/rk2/signals/${encodeURIComponent(context.component.id)}`}>{signal.name}</Link> : <span>{signal.name}</span>}
{context && <div className="text-gray-600">{[context.unit.bmk, context.unit.name, formatComponentName(context.component)].filter(Boolean).join(' / ')}</div>}
{signal.description && <div className="text-gray-600">{signal.description}</div>}
</div>;
})}</td>
</tr>)}</tbody>
</table>
{visible.length === 0 && <p className="p-4">{ios.length === 0 ? 'Keine IOs für diese Anlage vorhanden.' : 'Keine IOs passend zum Filter.'}</p>}
</div>
</>;
}
@@ -0,0 +1,34 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import Modal from '@/components/ui/Modal';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { api_templates_fromUnit } from '@/actions/rk2/api-unit-templates';
import { UnitResponse } from '@/types/anlagen/units';
export function SaveTemplateDialog({ unit, onClose }: { unit: UnitResponse; onClose: () => void }) {
const [name, setName] = useState(unit.name);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [saved, setSaved] = useState(false);
return <Modal onClose={() => { if (!busy) onClose(); }}>
<form className="flex max-w-lg flex-col gap-3" onSubmit={async event => {
event.preventDefault();
if (busy || saved) return;
setBusy(true); setError('');
const result = await api_templates_fromUnit(unit.id, name);
if (result.success) setSaved(true); else setError(result.errors.join(', '));
setBusy(false);
}}>
<h2 className="text-lg font-semibold">Als Vorlage speichern</h2>
<p>Der gespeicherte Stand einschließlich Komponenten und Signalen wird übernommen. Speichere Änderungen an der Unit vorher.</p>
<Label htmlFor="template-name">Vorlagenname</Label>
<Input id="template-name" required value={name} disabled={busy || saved} onChange={e => setName(e.target.value)} />
{error && <p role="alert" className="text-red-600">{error}</p>}
{saved ? <p role="status">Vorlage gespeichert. <Link className="underline" href="/rk2/units/templates">Vorlagen öffnen</Link></p> : <Button disabled={busy || !name.trim()} type="submit">{busy ? 'Wird gespeichert …' : 'Vorlage speichern'}</Button>}
<Button type="button" variant="secondary" disabled={busy} onClick={onClose}>Schließen</Button>
</form>
</Modal>;
}
+5 -3
View File
@@ -11,8 +11,10 @@ import { GroupSelect } from "../groups/groupSelect";
import type { GroupResponse } from "@/types/anlagen/groups";
import type { UnitCopy, UnitResponse } from "@/types/anlagen/units";
export function UnitCopyDialog({ unit, groups, onClose }: {
export function UnitCopyDialog({ unit, groups, onClose, onCopy, title = 'Unit kopieren' }: {
unit: UnitResponse; groups: GroupResponse[]; onClose: () => void;
onCopy?: (data: UnitCopy) => Promise<ActionResult<UnitResponse>>;
title?: string;
}) {
const router = useRouter();
const [data, setData] = useState<UnitCopy>({
@@ -29,7 +31,7 @@ export function UnitCopyDialog({ unit, groups, onClose }: {
setBusy(true);
setError('');
try {
const result = await api_units_copy(unit.id, data);
const result = onCopy ? await onCopy(data) : await api_units_copy(unit.id, data);
if (!result.success) {
setError(Array.isArray(result.errors) ? result.errors.join(', ') : String(result.errors));
setBusy(false);
@@ -46,7 +48,7 @@ export function UnitCopyDialog({ unit, groups, onClose }: {
return <Modal onClose={() => { if (!busy) onClose(); }}>
<div className="w-full max-w-lg">
<h2 className="mb-4 text-lg font-semibold">Unit kopieren</h2>
<h2 className="mb-4 text-lg font-semibold">{title}</h2>
<p className="mb-4 text-sm">Komponenten und Signale werden kopiert. IO-Zuordnungen bleiben leer. Kopiert wird der gespeicherte Stand.</p>
<form onSubmit={submit} className="flex flex-col gap-3">
<fieldset disabled={busy} className="flex flex-col gap-3">
+4
View File
@@ -13,6 +13,7 @@ import { UnitCopyDialog } from "./unitCopyDialog";
import { Button } from "@/components/ui/button";
import { useRouter } from "next/navigation";
import { api_units_delete } from "@/actions/rk2/api-units";
import { SaveTemplateDialog } from './saveTemplateDialog';
@@ -33,6 +34,7 @@ export const UnitEdit = ({ anlage, groups, selectedUnit, componentTypes,componen
const { getGroupById } = useGroups({ groups });
const [showSelectGroup, setShowSelectGroup] = useState(false);
const [showCopy, setShowCopy] = useState(false);
const [showTemplate, setShowTemplate] = useState(false);
const [showDelete, setShowDelete] = useState(false);
const [deleting, setDeleting] = useState(false);
const [deleteError, setDeleteError] = useState('');
@@ -83,6 +85,8 @@ export const UnitEdit = ({ anlage, groups, selectedUnit, componentTypes,componen
return (
<div className="" >
{selectedUnit && <Button className="mb-4 mr-2" type="button" variant="secondary" onClick={() => setShowTemplate(true)}>Als Vorlage speichern</Button>}
{showTemplate && selectedUnit && <SaveTemplateDialog unit={selectedUnit} onClose={() => setShowTemplate(false)} />}
{selectedUnit && <Button className="mb-4" type="button" variant="secondary" onClick={() => setShowCopy(true)}>Unit kopieren</Button>}
{showCopy && selectedUnit && <UnitCopyDialog unit={selectedUnit} groups={groups} onClose={() => setShowCopy(false)} />}
{selectedUnit && <Button className="mb-4 ml-2" type="button" variant="secondary" onClick={() => { setDeleteError(''); setShowDelete(true); }}>Unit löschen</Button>}
+147
View File
@@ -0,0 +1,147 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select } from '@/components/ui/select';
import Modal from '@/components/ui/Modal';
import { UnitTemplate, UnitTemplateData } from '@/types/anlagen/unit-templates';
import { ComponentCreate, ComponentDefaults, ComponentTypeDefinition } from '@/types/anlagen/components';
import { GroupResponse } from '@/types/anlagen/groups';
import { UnitType } from '@/types/anlagen/units';
import { SignalType } from '@/types/anlagen/signals';
import { api_templates_save, api_templates_delete, api_templates_insert } from '@/actions/rk2/api-unit-templates';
import { UnitCopyDialog } from './unitCopyDialog';
import { PropertyField } from './propertyFields';
export function UnitTemplates({ initial, groups, componentTypes, componentDefaults }: {
initial: UnitTemplate[]; groups: GroupResponse[]; componentTypes: ComponentTypeDefinition[]; componentDefaults: ComponentDefaults[];
}) {
const router = useRouter();
const [templates, setTemplates] = useState(initial);
const [editing, setEditing] = useState<UnitTemplateData>();
const [editingId, setEditingId] = useState<string>();
const [inserting, setInserting] = useState<UnitTemplate>();
const [deleting, setDeleting] = useState<UnitTemplate>();
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [status, setStatus] = useState('');
const [addType, setAddType] = useState(componentTypes[0]?.type ?? '');
const patchComponent = (index: number, patch: Partial<ComponentCreate>) => setEditing(current => current && ({
...current, components: current.components.map((c, i) => i === index ? { ...c, ...patch } : c),
}));
const startEdit = (template?: UnitTemplate) => {
setError(''); setStatus(''); setEditingId(template?.id);
setEditing(template ? structuredClone(template) : { name: '', type: UnitType.BAND, components: [], signals: [] });
};
return <div className="flex flex-col gap-4">
<Button type="button" className="self-start" onClick={() => startEdit()}>Neue Vorlage</Button>
{status && <p role="status">{status}</p>}
{!templates.length && <p>Noch keine Vorlagen. Lege eine Vorlage an oder speichere eine bestehende Unit als Vorlage.</p>}
{templates.map(template => <div key={template.id} className="flex flex-wrap items-center gap-3 rounded border p-3">
<div className="mr-auto"><strong>{template.name}</strong><p>{template.type} · {template.components.length} Komponenten · {template.signals.length} Signale</p></div>
<Button type="button" onClick={() => setInserting(template)}>Aus Vorlage hinzufügen</Button>
<Button type="button" variant="secondary" onClick={() => startEdit(template)}>Bearbeiten</Button>
<Button type="button" variant="secondary" onClick={() => { setError(''); setDeleting(template); }}>Löschen</Button>
</div>)}
{inserting && <UnitCopyDialog title="Aus Vorlage hinzufügen" groups={groups}
unit={{ ...inserting, groupId: undefined, components: inserting.components.map((c, i) => ({ ...c, id: String(i) })) }}
onCopy={data => api_templates_insert(inserting.id, data)} onClose={() => setInserting(undefined)} />}
{deleting && <Modal onClose={() => { if (!busy) setDeleting(undefined); }}>
<h2 className="mb-3 font-semibold">Vorlage „{deleting.name}“ löschen?</h2>
<p className="mb-3">Bereits eingefügte Units bleiben erhalten.</p>
{error && <p role="alert" className="text-red-600">{error}</p>}
<Button disabled={busy} onClick={async () => {
if (busy) return;
setBusy(true); setError('');
const result = await api_templates_delete(deleting.id);
if (result.success) { setTemplates(current => current.filter(t => t.id !== deleting.id)); setDeleting(undefined); router.refresh(); }
else setError(result.errors.join(', '));
setBusy(false);
}}>Endgültig löschen</Button>
<Button className="ml-2" variant="secondary" disabled={busy} onClick={() => setDeleting(undefined)}>Abbrechen</Button>
</Modal>}
{editing && <Modal onClose={() => { if (!busy) setEditing(undefined); }}>
<form className="max-h-[80vh] w-full max-w-4xl overflow-auto p-2" onSubmit={async event => {
event.preventDefault();
if (busy) return;
setBusy(true); setError('');
const result = await api_templates_save(editing, editingId);
if (result.success) {
setTemplates(current => [...current.filter(t => t.id !== result.data.id), result.data].sort((a, b) => a.name.localeCompare(b.name)));
setEditing(undefined); setStatus('Vorlage gespeichert.'); router.refresh();
} else setError(result.errors.join(', '));
setBusy(false);
}}>
<h2 className="mb-4 text-lg font-semibold">{editingId ? 'Vorlage bearbeiten' : 'Neue Unit-Vorlage'}</h2>
<fieldset disabled={busy} className="flex flex-col gap-4">
<div className="grid grid-cols-2 gap-3">
{(['name', 'prefix', 'bmk', 'postfix', 'info'] as const).map(key => <div key={key}>
<Label htmlFor={`tpl-${key}`}>{({ name: 'Vorlagenname', prefix: 'Prefix', bmk: 'BMK', postfix: 'Postfix', info: 'Info' })[key]}</Label>
<Input id={`tpl-${key}`} required={key === 'name'} value={editing[key] ?? ''} onChange={e => setEditing({ ...editing, [key]: e.target.value })} />
</div>)}
<div><Label htmlFor="tpl-type">Unit-Typ</Label><Select id="tpl-type" value={editing.type} onChange={e => setEditing({ ...editing, type: e.target.value as UnitType })}>
{Object.values(UnitType).map(type => <option key={type}>{type}</option>)}
</Select></div>
</div>
<h3 className="font-semibold">Komponenten</h3>
{editing.components.map((component, index) => {
const definition = componentTypes.find(t => t.type === component.type);
return <div key={index} className="flex flex-col gap-3 rounded border p-3">
<div className="grid grid-cols-2 gap-2">
<div><Label>Komponententyp</Label><Select value={component.type} onChange={e => patchComponent(index, { type: e.target.value, properties: Object.fromEntries((componentTypes.find(t => t.type === e.target.value)?.properties ?? []).map(p => [p.key, p.defaultValue])) })}>
{!definition && <option value={component.type}>{component.type}</option>}
{componentTypes.map(t => <option key={t.type} value={t.type}>{t.label}</option>)}
</Select></div>
{(['name', 'prefix', 'postfix'] as const).map(key => <div key={key}><Label>{({ name: 'Name', prefix: 'Prefix', postfix: 'Postfix' })[key]}</Label>
<Input required={key === 'name'} value={component[key] ?? ''} onChange={e => patchComponent(index, { [key]: e.target.value })} />
</div>)}
<div><Label>Index</Label><Input type="number" value={component.index ?? ''} onChange={e => patchComponent(index, { index: e.target.value === '' ? undefined : Number(e.target.value) })} /></div>
</div>
<div className="flex flex-wrap gap-3">{definition?.properties.map(property => <PropertyField key={property.key} name={property.key} propertyType={property}
value={component.properties?.[property.key] ?? property.defaultValue ?? ''}
setPropValue={(key, value) => patchComponent(index, { properties: { ...component.properties, [key]: property.type === 'number' ? Number(value) : value } })} />)}</div>
<h4 className="font-semibold">Signale</h4>
{editing.signals.map((signal, signalIndex) => signal.componentIndex === index && <div className="grid grid-cols-2 gap-2 border-t pt-2" key={signalIndex}>
<div><Label>Signalname</Label><Input required value={signal.name} onChange={e => setEditing({ ...editing, signals: editing.signals.map((s, i) => i === signalIndex ? { ...s, name: e.target.value } : s) })} /></div>
<div><Label>Signaltyp</Label><Select value={signal.type} onChange={e => setEditing({ ...editing, signals: editing.signals.map((s, i) => i === signalIndex ? { ...s, type: e.target.value as SignalType } : s) })}>
{Object.values(SignalType).map(t => <option key={t}>{t}</option>)}
</Select></div>
<div><Label>Beschreibung</Label><Input value={signal.description ?? ''} onChange={e => setEditing({ ...editing, signals: editing.signals.map((s, i) => i === signalIndex ? { ...s, description: e.target.value } : s) })} /></div>
<Button type="button" variant="secondary" onClick={() => setEditing({ ...editing, signals: editing.signals.filter((_, i) => i !== signalIndex) })}>Signal entfernen</Button>
</div>)}
<div className="flex gap-2">
<Button type="button" variant="secondary" onClick={() => setEditing({ ...editing, signals: [...editing.signals, { componentIndex: index, name: '', type: SignalType.DIGITAL_INPUT }] })}>Signal hinzufügen</Button>
<Button type="button" variant="secondary" onClick={() => setEditing({ ...editing,
components: editing.components.filter((_, i) => i !== index),
signals: editing.signals.filter(s => s.componentIndex !== index).map(s => ({ ...s, componentIndex: s.componentIndex > index ? s.componentIndex - 1 : s.componentIndex })),
})}>Komponente entfernen</Button>
</div>
</div>;
})}
<div className="flex items-end gap-3">
<div><Label htmlFor="tpl-add-component">Neue Komponente</Label><Select id="tpl-add-component" value={addType} onChange={e => setAddType(e.target.value)}>
{componentTypes.map(type => <option key={type.type} value={type.type}>{type.label}</option>)}
</Select></div>
<Button type="button" variant="secondary" onClick={() => {
const type = componentTypes.find(t => t.type === addType);
if (!type) return;
const defaults = componentDefaults.find(d => d.type === type.type);
setEditing({ ...editing,
components: [...editing.components, { name: defaults?.name || type.label, type: type.type, properties: Object.fromEntries(type.properties.map(p => [p.key, p.defaultValue])) }],
signals: [...editing.signals, ...(defaults?.signals ?? []).map(s => ({ ...s, componentIndex: editing.components.length }))],
});
}}>Komponente hinzufügen</Button>
</div>
</fieldset>
{error && <p role="alert" className="my-3 text-red-600">{error}</p>}
<div className="mt-4 flex gap-2">
<Button type="submit" disabled={busy || !editing.name.trim()}>{busy ? 'Wird gespeichert …' : 'Vorlage speichern'}</Button>
<Button type="button" variant="secondary" disabled={busy} onClick={() => setEditing(undefined)}>Abbrechen</Button>
</div>
</form>
</Modal>}
</div>;
}