unit template
This commit is contained in:
1 parent
c15e69f7b5
commit
3bea468d23
11 files changed
+391
-4
No files matched your search
@@ -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>;
|
||||
}
|
||||
@@ -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">
|
||||
|
||||
@@ -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>}
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
Reference in new issue
Block a user