Compare commits
5 Commits
cdfc779bc8
...
155ccd016e
| Author | SHA1 | Date | |
|---|---|---|---|
| 155ccd016e | |||
| d0b2373cc1 | |||
| 72508a60bf | |||
| 00f7b4f1ce | |||
| 5f85074653 |
9
pom.xml
9
pom.xml
@@ -13,7 +13,7 @@
|
||||
|
||||
<groupId>de.assecutor</groupId>
|
||||
<artifactId>tasklist-editor</artifactId>
|
||||
<version>0.2.0</version>
|
||||
<version>0.9.2</version>
|
||||
<name>TaskList Editor</name>
|
||||
<description>n8n-inspired editor for task list workflows</description>
|
||||
|
||||
@@ -57,6 +57,13 @@
|
||||
<version>4.0.0</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Offizielles Anthropic-SDK: KI-Workflow-Assistent (Claude API). -->
|
||||
<dependency>
|
||||
<groupId>com.anthropic</groupId>
|
||||
<artifactId>anthropic-java</artifactId>
|
||||
<version>2.48.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-devtools</artifactId>
|
||||
|
||||
@@ -181,6 +181,70 @@ if (Drawflow && Drawflow.prototype) {
|
||||
|
||||
const editors = new WeakMap();
|
||||
|
||||
// --- Undo-Historie ---------------------------------------------------------
|
||||
// Nach jeder Canvas-Änderung wird ein Schnappschuss (Drawflow-Export)
|
||||
// abgelegt; Strg+Z bzw. der Rückgängig-Button stellt den vorherigen
|
||||
// Schnappschuss wieder her. Es sind maximal UNDO_LIMIT Schritte rücknehmbar.
|
||||
const UNDO_LIMIT = 10;
|
||||
|
||||
function currentSnapshot(state) {
|
||||
return JSON.stringify(state.editor.export());
|
||||
}
|
||||
|
||||
// Legt (um einen Tick verzögert) einen Schnappschuss ab. Mehrere Drawflow-
|
||||
// Events derselben Benutzeraktion (z. B. Knoten löschen inkl. seiner
|
||||
// Verbindungen) werden so zu einem einzigen Undo-Schritt zusammengefasst.
|
||||
function recordHistory(state) {
|
||||
if (state.undoSuppressed || state.undoScheduled) return;
|
||||
state.undoScheduled = true;
|
||||
setTimeout(() => {
|
||||
state.undoScheduled = false;
|
||||
if (state.undoSuppressed) return;
|
||||
const snap = currentSnapshot(state);
|
||||
const stack = state.history;
|
||||
if (stack.length && stack[stack.length - 1] === snap) return;
|
||||
stack.push(snap);
|
||||
// Basiszustand + UNDO_LIMIT rücknehmbare Schritte behalten.
|
||||
if (stack.length > UNDO_LIMIT + 1) stack.shift();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Setzt die Historie auf den aktuellen Zustand als neuen Basiszustand zurück
|
||||
// (z. B. nach dem Laden eines gespeicherten Canvas).
|
||||
function resetHistory(state) {
|
||||
state.history = [currentSnapshot(state)];
|
||||
}
|
||||
|
||||
// Stellt den vorherigen Schnappschuss wieder her; liefert false, wenn es
|
||||
// nichts zurückzunehmen gibt.
|
||||
function undoLast(state) {
|
||||
const stack = state.history;
|
||||
if (!stack || stack.length < 2) return false;
|
||||
stack.pop(); // aktueller Zustand
|
||||
const previous = stack[stack.length - 1];
|
||||
state.undoSuppressed = true;
|
||||
try {
|
||||
state.editor.import(JSON.parse(previous));
|
||||
} finally {
|
||||
state.undoSuppressed = false;
|
||||
}
|
||||
notifyCanvasRestored(state);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Meldet dem Server die nach einem Undo vorhandenen Knoten, damit dieser
|
||||
// seine BlockInstances (inkl. der Einstellungen wiederhergestellter Blöcke)
|
||||
// abgleichen kann.
|
||||
function notifyCanvasRestored(state) {
|
||||
if (!state.host || !state.host.$server) return;
|
||||
const data = state.editor.drawflow.drawflow[state.editor.module].data;
|
||||
const nodes = Object.keys(data).map(id => ({
|
||||
id: parseInt(id, 10),
|
||||
typeId: data[id].data ? data[id].data.typeId : null
|
||||
}));
|
||||
state.host.$server.onCanvasRestored(JSON.stringify(nodes));
|
||||
}
|
||||
|
||||
if (!window.__taskListEditorDragInit) {
|
||||
window.__taskListEditorDragInit = true;
|
||||
document.addEventListener('dragstart', e => {
|
||||
@@ -261,9 +325,14 @@ function attach(host) {
|
||||
const state = {
|
||||
editor,
|
||||
container,
|
||||
registry: new Map()
|
||||
host,
|
||||
registry: new Map(),
|
||||
history: [],
|
||||
undoSuppressed: false,
|
||||
undoScheduled: false
|
||||
};
|
||||
editors.set(host, state);
|
||||
resetHistory(state);
|
||||
|
||||
// Hindernis-bewusste Linienführung. Reroute-Teilsegmente
|
||||
// (type != 'openclose') nutzen die einfache vertikale Kurve.
|
||||
@@ -284,14 +353,12 @@ function attach(host) {
|
||||
const def = state.registry.get(typeId);
|
||||
if (!def) return;
|
||||
|
||||
const rect = container.getBoundingClientRect();
|
||||
const zoom = editor.zoom;
|
||||
// Greif-Offset abziehen, damit der Knoten an seiner gezogenen Position
|
||||
// liegt (linke obere Ecke wie während des Ziehens, nicht an der Maus).
|
||||
const px = (e.clientX - rect.left - editor.canvas_x - dragGrabOffset.x) / zoom;
|
||||
const py = (e.clientY - rect.top - editor.canvas_y - dragGrabOffset.y) / zoom;
|
||||
|
||||
addNodeInternal(host, def, px, py);
|
||||
// Greif-Offset in Canvas-Einheiten abziehen (nicht in Bildschirm-
|
||||
// Pixeln): So bleibt der Mauszeiger in jeder Zoomstufe an derselben
|
||||
// relativen Stelle im erzeugten Knoten, statt dass der Knoten beim
|
||||
// Herauszoomen um den hochgerechneten Offset neben der Maus landet.
|
||||
const { x, y } = toCanvasPoint(state, e.clientX, e.clientY);
|
||||
addNodeInternal(host, def, x - dragGrabOffset.x, y - dragGrabOffset.y);
|
||||
});
|
||||
|
||||
editor.on('nodeSelected', id => {
|
||||
@@ -362,6 +429,14 @@ function attach(host) {
|
||||
editor.on('nodeRemoved', refresh);
|
||||
editor.on('import', refresh);
|
||||
|
||||
// Undo-Historie: jede strukturelle Änderung erzeugt einen Schnappschuss.
|
||||
const record = () => recordHistory(state);
|
||||
editor.on('nodeCreated', record);
|
||||
editor.on('nodeRemoved', record);
|
||||
editor.on('nodeMoved', record);
|
||||
editor.on('connectionCreated', record);
|
||||
editor.on('connectionRemoved', record);
|
||||
|
||||
// Klick in die Nähe einer Verbindung (auf leerem Canvas-Hintergrund) wählt
|
||||
// diese aus – robuster als das exakte Treffen der dünnen Linie. Läuft in der
|
||||
// Capture-Phase vor Drawflow, um das Verschieben/Deselektieren zu verhindern.
|
||||
@@ -376,49 +451,68 @@ function attach(host) {
|
||||
selectConnection(state, path);
|
||||
}, true);
|
||||
|
||||
// Verschieben von Knoten mit der RECHTEN Maustaste. Drawflow zieht Knoten
|
||||
// nur mit links; das Ziehen mit rechts wird hier eigenständig umgesetzt.
|
||||
// Rechte Maustaste: auf einem Knoten wird der Knoten verschoben (Drawflow
|
||||
// zieht Knoten nur mit links), auf dem freien Canvas wird die gesamte
|
||||
// Ansicht verschoben (Panning).
|
||||
let rightDrag = null;
|
||||
let suppressContextMenu = false;
|
||||
let rightPan = null;
|
||||
container.addEventListener('mousedown', e => {
|
||||
if (e.button !== 2) return;
|
||||
const nodeEl = e.target instanceof Element ? e.target.closest('.drawflow-node') : null;
|
||||
if (!nodeEl) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation(); // Drawflows eigene (Links-)Drag-Logik nicht auslösen
|
||||
rightDrag = {
|
||||
nodeEl,
|
||||
id: nodeEl.id.replace('node-', ''),
|
||||
lastX: e.clientX,
|
||||
lastY: e.clientY
|
||||
};
|
||||
suppressContextMenu = true;
|
||||
const nodeEl = e.target instanceof Element ? e.target.closest('.drawflow-node') : null;
|
||||
if (nodeEl) {
|
||||
rightDrag = {
|
||||
nodeEl,
|
||||
id: nodeEl.id.replace('node-', ''),
|
||||
lastX: e.clientX,
|
||||
lastY: e.clientY
|
||||
};
|
||||
} else {
|
||||
rightPan = { lastX: e.clientX, lastY: e.clientY };
|
||||
}
|
||||
}, true);
|
||||
|
||||
const onRightMove = e => {
|
||||
if (rightPan) {
|
||||
editor.canvas_x += e.clientX - rightPan.lastX;
|
||||
editor.canvas_y += e.clientY - rightPan.lastY;
|
||||
rightPan.lastX = e.clientX;
|
||||
rightPan.lastY = e.clientY;
|
||||
editor.precanvas.style.transform =
|
||||
'translate(' + editor.canvas_x + 'px, ' + editor.canvas_y + 'px) scale(' + editor.zoom + ')';
|
||||
return;
|
||||
}
|
||||
if (!rightDrag) return;
|
||||
const zoom = editor.zoom || 1;
|
||||
const newLeft = rightDrag.nodeEl.offsetLeft + (e.clientX - rightDrag.lastX) / zoom;
|
||||
const newTop = rightDrag.nodeEl.offsetTop + (e.clientY - rightDrag.lastY) / zoom;
|
||||
rightDrag.lastX = e.clientX;
|
||||
rightDrag.lastY = e.clientY;
|
||||
rightDrag.moved = true;
|
||||
rightDrag.nodeEl.style.left = newLeft + 'px';
|
||||
rightDrag.nodeEl.style.top = newTop + 'px';
|
||||
const data = editor.drawflow.drawflow[editor.module].data[rightDrag.id];
|
||||
if (data) { data.pos_x = newLeft; data.pos_y = newTop; }
|
||||
editor.updateConnectionNodes('node-' + rightDrag.id);
|
||||
};
|
||||
const onRightUp = () => { rightDrag = null; };
|
||||
const onRightUp = () => {
|
||||
// Ein per Rechts-Drag verschobener Knoten löst Drawflows nodeMoved
|
||||
// nicht aus -> Undo-Schnappschuss hier ablegen.
|
||||
if (rightDrag && rightDrag.moved) recordHistory(state);
|
||||
rightDrag = null;
|
||||
rightPan = null;
|
||||
};
|
||||
document.addEventListener('mousemove', onRightMove);
|
||||
document.addEventListener('mouseup', onRightUp);
|
||||
|
||||
// Browser-Kontextmenü nach einem Rechts-Ziehen auf einem Knoten unterdrücken.
|
||||
// Rechts dient nur zum Verschieben: Browser-Kontextmenü unterdrücken und
|
||||
// das Event in der Capture-Phase stoppen, bevor Drawflows eigener
|
||||
// contextmenu-Handler das Lösch-"x" am selektierten Knoten einblendet.
|
||||
container.addEventListener('contextmenu', e => {
|
||||
if (suppressContextMenu) {
|
||||
e.preventDefault();
|
||||
suppressContextMenu = false;
|
||||
}
|
||||
});
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}, true);
|
||||
|
||||
// Zoomen mit dem Mausrad (ohne Strg). Läuft in der Capture-Phase und stoppt
|
||||
// die Propagation, damit Drawflows eigenes Strg+Rad-Zoom nicht zusätzlich
|
||||
@@ -455,8 +549,25 @@ function attach(host) {
|
||||
editor.removeConnection();
|
||||
};
|
||||
document.addEventListener('keydown', deleteSelectedConnection);
|
||||
|
||||
// Strg+Z / Cmd+Z: letzte Canvas-Änderung zurücknehmen. Eingaben in
|
||||
// Textfeldern und geöffneten Dialogen bleiben unangetastet.
|
||||
const undoKeyHandler = e => {
|
||||
if (!(e.ctrlKey || e.metaKey) || e.shiftKey || (e.key !== 'z' && e.key !== 'Z')) return;
|
||||
const active = document.activeElement;
|
||||
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA'
|
||||
|| active.isContentEditable
|
||||
|| (active.closest && active.closest('vaadin-dialog-overlay')))) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
undoLast(state);
|
||||
};
|
||||
document.addEventListener('keydown', undoKeyHandler);
|
||||
|
||||
state.cleanup = () => {
|
||||
document.removeEventListener('keydown', deleteSelectedConnection);
|
||||
document.removeEventListener('keydown', undoKeyHandler);
|
||||
document.removeEventListener('mousemove', onRightMove);
|
||||
document.removeEventListener('mouseup', onRightUp);
|
||||
container.removeEventListener('wheel', onWheelZoom, { capture: true });
|
||||
@@ -466,14 +577,16 @@ function attach(host) {
|
||||
}
|
||||
|
||||
// Wandelt Client-Koordinaten in das (unskalierte) Canvas-Koordinatensystem um,
|
||||
// in dem auch die Verbindungspfade definiert sind.
|
||||
// in dem auch die Verbindungspfade definiert sind. Das Rect des precanvas
|
||||
// enthält bereits translate UND scale (inkl. transform-origin in der Mitte),
|
||||
// daher genügt es, den skalierten Abstand zurückzurechnen.
|
||||
function toCanvasPoint(state, clientX, clientY) {
|
||||
const editor = state.editor;
|
||||
const rect = state.container.getBoundingClientRect();
|
||||
const rect = editor.precanvas.getBoundingClientRect();
|
||||
const zoom = editor.zoom || 1;
|
||||
return {
|
||||
x: (clientX - rect.left - editor.canvas_x) / zoom,
|
||||
y: (clientY - rect.top - editor.canvas_y) / zoom,
|
||||
x: (clientX - rect.left) / zoom,
|
||||
y: (clientY - rect.top) / zoom,
|
||||
zoom
|
||||
};
|
||||
}
|
||||
@@ -580,6 +693,7 @@ window.taskListEditor = {
|
||||
editor.removeNodeOutput(nodeId, `output_${current}`);
|
||||
current--;
|
||||
}
|
||||
recordHistory(state);
|
||||
requestAnimationFrame(() => refreshValidity(state));
|
||||
},
|
||||
updateNodeLabel(host, nodeId, label) {
|
||||
@@ -589,12 +703,23 @@ window.taskListEditor = {
|
||||
if (!node) return;
|
||||
const html = buildNodeHtml(label, state.registry.get(node.data.typeId)?.color || '#444');
|
||||
state.editor.updateNodeDataFromId(nodeId, { ...node.data, label });
|
||||
// Auch das im Graphen hinterlegte HTML aktualisieren, damit Export,
|
||||
// Laden und Undo den neuen Titel anzeigen.
|
||||
const nodeData = state.editor.drawflow.drawflow[state.editor.module].data[nodeId];
|
||||
if (nodeData) nodeData.html = html;
|
||||
const el = state.container.querySelector(`#node-${nodeId} .drawflow_content_node`);
|
||||
if (el) el.innerHTML = html;
|
||||
recordHistory(state);
|
||||
},
|
||||
undo(host) {
|
||||
const state = editors.get(host);
|
||||
return state ? undoLast(state) : false;
|
||||
},
|
||||
clear(host) {
|
||||
const state = editors.get(host);
|
||||
if (state) state.editor.clear();
|
||||
if (!state) return;
|
||||
state.editor.clear();
|
||||
recordHistory(state);
|
||||
},
|
||||
exportGraph(host) {
|
||||
const state = editors.get(host);
|
||||
@@ -634,6 +759,8 @@ window.taskListEditor = {
|
||||
state.editor.addConnection(ids[i], ids[i + 1], 'output_1', 'input_1');
|
||||
}
|
||||
|
||||
// Frisch geladener Stand ist der neue Basiszustand der Undo-Historie.
|
||||
resetHistory(state);
|
||||
return JSON.stringify(ids);
|
||||
},
|
||||
importGraph(host, graphJson) {
|
||||
@@ -641,6 +768,8 @@ window.taskListEditor = {
|
||||
if (!graphJson) return;
|
||||
try {
|
||||
state.editor.import(JSON.parse(graphJson));
|
||||
// Frisch geladener Stand ist der neue Basiszustand der Undo-Historie.
|
||||
resetHistory(state);
|
||||
} catch (e) {
|
||||
console.error('importGraph failed', e);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,16 @@ public class NodeEditor extends Div {
|
||||
getElement().executeJs("window.taskListEditor.clear(this)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Nimmt die letzte Canvas-Änderung zurück (maximal 10 Schritte). Der
|
||||
* Callback erhält {@code true}, wenn ein Schritt zurückgenommen wurde,
|
||||
* sonst {@code false}.
|
||||
*/
|
||||
public void undo(SerializableConsumer<Boolean> callback) {
|
||||
getElement().executeJs("return window.taskListEditor.undo(this)")
|
||||
.then(Boolean.class, callback::accept);
|
||||
}
|
||||
|
||||
/**
|
||||
* Liest den aktuellen Drawflow-Graphen (Knoten + Verbindungen) als
|
||||
* JSON-String aus dem Client und übergibt ihn an den Callback.
|
||||
@@ -115,6 +125,10 @@ public class NodeEditor extends Div {
|
||||
return addListener(NodeRemovedEvent.class, listener);
|
||||
}
|
||||
|
||||
public Registration addCanvasRestoredListener(ComponentEventListener<CanvasRestoredEvent> listener) {
|
||||
return addListener(CanvasRestoredEvent.class, listener);
|
||||
}
|
||||
|
||||
@ClientCallable
|
||||
private void onNodeAdded(int nodeId, String typeId) {
|
||||
fireEvent(new NodeAddedEvent(this, nodeId, typeId));
|
||||
@@ -140,6 +154,11 @@ public class NodeEditor extends Div {
|
||||
fireEvent(new NodeRemovedEvent(this, nodeId));
|
||||
}
|
||||
|
||||
@ClientCallable
|
||||
private void onCanvasRestored(String nodesJson) {
|
||||
fireEvent(new CanvasRestoredEvent(this, nodesJson));
|
||||
}
|
||||
|
||||
public static class NodeAddedEvent extends ComponentEvent<NodeEditor> {
|
||||
private final int nodeId;
|
||||
private final String typeId;
|
||||
@@ -192,4 +211,20 @@ public class NodeEditor extends Div {
|
||||
|
||||
public int nodeId() { return nodeId; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Wird nach einem Undo gefeuert und enthält die danach auf dem Canvas
|
||||
* vorhandenen Knoten als JSON-Array aus Objekten mit {@code id} und
|
||||
* {@code typeId}, damit der Server seinen Zustand abgleichen kann.
|
||||
*/
|
||||
public static class CanvasRestoredEvent extends ComponentEvent<NodeEditor> {
|
||||
private final String nodesJson;
|
||||
|
||||
public CanvasRestoredEvent(NodeEditor source, String nodesJson) {
|
||||
super(source, true);
|
||||
this.nodesJson = nodesJson;
|
||||
}
|
||||
|
||||
public String nodesJson() { return nodesJson; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +188,7 @@ public class BlockTypeRegistry {
|
||||
11,
|
||||
1, 1,
|
||||
List.of(
|
||||
PropertyDefinition.textArea("choices", "Statusoptionen (eine pro Zeile)"),
|
||||
PropertyDefinition.choiceList("choices", "Statusoptionen"),
|
||||
PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
|
||||
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
|
||||
)
|
||||
@@ -208,7 +208,6 @@ public class BlockTypeRegistry {
|
||||
1, 1,
|
||||
List.of(
|
||||
PropertyDefinition.fieldList("fields", "Textfelder (Titel + Platzhalter)"),
|
||||
PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
|
||||
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
|
||||
)
|
||||
));
|
||||
@@ -223,7 +222,6 @@ public class BlockTypeRegistry {
|
||||
1, 1,
|
||||
List.of(
|
||||
PropertyDefinition.fieldList("fields", "Zahlenfelder (Titel + Platzhalter)"),
|
||||
PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
|
||||
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
|
||||
)
|
||||
));
|
||||
@@ -238,7 +236,6 @@ public class BlockTypeRegistry {
|
||||
1, 1,
|
||||
List.of(
|
||||
PropertyDefinition.nameList("entries", "Name der Checkboxen"),
|
||||
PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
|
||||
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
|
||||
)
|
||||
));
|
||||
|
||||
@@ -5,17 +5,18 @@ import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
||||
|
||||
/**
|
||||
* Ein einzelnes Eingabefeld eines Listen-Text-Tasks (Typ 12).
|
||||
* Definiert Titel und Platzhalter eines vom Bearbeiter auszufüllenden
|
||||
* Textfeldes.
|
||||
* Definiert Titel, Platzhalter und Pflichtfeld-Kennzeichen eines vom
|
||||
* Bearbeiter auszufüllenden Textfeldes.
|
||||
*
|
||||
* <p>{@code null}-Felder werden ausgelassen.
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
@JsonPropertyOrder({"title", "placeholder"})
|
||||
@JsonPropertyOrder({"title", "placeholder", "required"})
|
||||
public class FieldDto {
|
||||
|
||||
private String title;
|
||||
private String placeholder;
|
||||
private Boolean required;
|
||||
|
||||
public FieldDto() {
|
||||
}
|
||||
@@ -25,6 +26,14 @@ public class FieldDto {
|
||||
this.placeholder = placeholder;
|
||||
}
|
||||
|
||||
public Boolean getRequired() {
|
||||
return required;
|
||||
}
|
||||
|
||||
public void setRequired(Boolean required) {
|
||||
this.required = required;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
@@ -26,4 +26,8 @@ public record PropertyDefinition(String id, String label, PropertyType type, Obj
|
||||
public static PropertyDefinition nameList(String id, String label) {
|
||||
return new PropertyDefinition(id, label, PropertyType.NAME_LIST, List.of());
|
||||
}
|
||||
|
||||
public static PropertyDefinition choiceList(String id, String label) {
|
||||
return new PropertyDefinition(id, label, PropertyType.CHOICE_LIST, List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,5 +8,10 @@ public enum PropertyType {
|
||||
/** Wiederholbare Liste aus Eingabefeldern mit Titel und Platzhalter. */
|
||||
FIELD_LIST,
|
||||
/** Wiederholbare Liste aus reinen Namens-Einträgen (ein Textfeld je Zeile). */
|
||||
NAME_LIST
|
||||
NAME_LIST,
|
||||
/**
|
||||
* Wiederholbare Liste aus Auswahloptionen (ein Textfeld je Zeile,
|
||||
* ohne Pflichtfeld-Kennzeichen).
|
||||
*/
|
||||
CHOICE_LIST
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package de.assecutor.tasklisteditor.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
/**
|
||||
@@ -14,6 +15,10 @@ public class TaskEntryDto {
|
||||
@JsonProperty("query_remark")
|
||||
private boolean queryRemark;
|
||||
|
||||
/** Pflichtfeld-Kennzeichen (nur bei Listen-Tasks gesetzt, sonst ausgelassen). */
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
private Boolean required;
|
||||
|
||||
public TaskEntryDto() {
|
||||
}
|
||||
|
||||
@@ -46,4 +51,12 @@ public class TaskEntryDto {
|
||||
public void setQueryRemark(boolean queryRemark) {
|
||||
this.queryRemark = queryRemark;
|
||||
}
|
||||
|
||||
public Boolean getRequired() {
|
||||
return required;
|
||||
}
|
||||
|
||||
public void setRequired(Boolean required) {
|
||||
this.required = required;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,22 @@ public class TaskListExporter {
|
||||
}
|
||||
|
||||
public List<TaskDto> export(String drawflowJson, Map<Integer, BlockInstance> instances) {
|
||||
return export(drawflowJson, instances, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Variante für den KI-Assistenten: enthält auch die virtuellen Start-/
|
||||
* Abschluss-Markierungen (damit das Modell den vollständigen Ablauf sieht
|
||||
* und sie im geänderten Workflow erhält) und verzichtet auf die
|
||||
* Vollständigkeits-Validierung, damit auch unfertige Workflows als
|
||||
* Kontext dienen können.
|
||||
*/
|
||||
public List<TaskDto> exportForAssistant(String drawflowJson, Map<Integer, BlockInstance> instances) {
|
||||
return export(drawflowJson, instances, true);
|
||||
}
|
||||
|
||||
private List<TaskDto> export(String drawflowJson, Map<Integer, BlockInstance> instances,
|
||||
boolean forAssistant) {
|
||||
List<TaskDto> tasks = new ArrayList<>();
|
||||
if (drawflowJson == null || drawflowJson.isBlank()) {
|
||||
return tasks;
|
||||
@@ -51,7 +67,9 @@ public class TaskListExporter {
|
||||
}
|
||||
// Ein vollständiger Workflow muss mit einem Start- und einem Abschluss-
|
||||
// Element gerahmt und beide müssen verdrahtet sein.
|
||||
validateWorkflow(data, instances);
|
||||
if (!forAssistant) {
|
||||
validateWorkflow(data, instances);
|
||||
}
|
||||
|
||||
if (!data.isObject() || data.isEmpty()) {
|
||||
return tasks;
|
||||
@@ -67,7 +85,7 @@ public class TaskListExporter {
|
||||
}
|
||||
// Rein virtuelle Blöcke (Start/Abschluss) sind nur Workflow-Markierungen
|
||||
// und gehören nicht in die exportierte Task-Liste.
|
||||
if (instance.type().isVirtual()) {
|
||||
if (!forAssistant && instance.type().isVirtual()) {
|
||||
continue;
|
||||
}
|
||||
TaskDto task = toTask(instance);
|
||||
@@ -230,7 +248,10 @@ public class TaskListExporter {
|
||||
}
|
||||
|
||||
if (v.containsKey("choices")) {
|
||||
task.setChoices(parseChoices(asText(v.get("choices"))));
|
||||
Object raw = v.get("choices");
|
||||
task.setChoices(raw instanceof List<?> list
|
||||
? parseChoices(list)
|
||||
: parseChoices(asText(raw)));
|
||||
}
|
||||
|
||||
if (v.containsKey("fields")) {
|
||||
@@ -273,13 +294,30 @@ public class TaskListExporter {
|
||||
if (o instanceof Map<?, ?> m) {
|
||||
String text = m.get("title") == null ? "" : m.get("title").toString().trim();
|
||||
if (!text.isEmpty()) {
|
||||
entries.add(new TaskEntryDto(code++, text, queryRemark));
|
||||
TaskEntryDto entry = new TaskEntryDto(code++, text, queryRemark);
|
||||
entry.setRequired(asBool(m.get("required")));
|
||||
entries.add(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
return entries.isEmpty() ? null : entries;
|
||||
}
|
||||
|
||||
/** Variante für den Zeilen-Editor: Liste aus {@code {title}}-Einträgen. */
|
||||
private List<ChoiceDto> parseChoices(List<?> raw) {
|
||||
List<ChoiceDto> choices = new ArrayList<>();
|
||||
int ret = 1;
|
||||
for (Object o : raw) {
|
||||
if (o instanceof Map<?, ?> m) {
|
||||
String text = m.get("title") == null ? "" : m.get("title").toString().trim();
|
||||
if (!text.isEmpty()) {
|
||||
choices.add(new ChoiceDto(text, ret++));
|
||||
}
|
||||
}
|
||||
}
|
||||
return choices.isEmpty() ? null : choices;
|
||||
}
|
||||
|
||||
private List<ChoiceDto> parseChoices(String raw) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
return null;
|
||||
@@ -305,7 +343,9 @@ public class TaskListExporter {
|
||||
String title = m.get("title") == null ? "" : m.get("title").toString().trim();
|
||||
String placeholder = m.get("placeholder") == null ? "" : m.get("placeholder").toString().trim();
|
||||
if (!title.isEmpty() || !placeholder.isEmpty()) {
|
||||
fields.add(new FieldDto(title, placeholder));
|
||||
FieldDto field = new FieldDto(title, placeholder);
|
||||
field.setRequired(asBool(m.get("required")));
|
||||
fields.add(field);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package de.assecutor.tasklisteditor.service;
|
||||
|
||||
import de.assecutor.tasklisteditor.model.BlockType;
|
||||
import de.assecutor.tasklisteditor.model.BlockTypeRegistry;
|
||||
import de.assecutor.tasklisteditor.model.ChoiceDto;
|
||||
import de.assecutor.tasklisteditor.model.FieldDto;
|
||||
import de.assecutor.tasklisteditor.model.PropertyDefinition;
|
||||
import de.assecutor.tasklisteditor.model.TaskDto;
|
||||
@@ -69,6 +70,7 @@ public class TaskListImporter {
|
||||
Object value = switch (def.type()) {
|
||||
case FIELD_LIST -> fieldRows(task);
|
||||
case NAME_LIST -> entryRows(task);
|
||||
case CHOICE_LIST -> choiceRows(task);
|
||||
default -> scalarValue(def, task);
|
||||
};
|
||||
values.put(def.id(), value);
|
||||
@@ -103,6 +105,7 @@ public class TaskListImporter {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("title", field.getTitle() == null ? "" : field.getTitle());
|
||||
row.put("placeholder", field.getPlaceholder() == null ? "" : field.getPlaceholder());
|
||||
row.put("required", Boolean.TRUE.equals(field.getRequired()));
|
||||
rows.add(row);
|
||||
}
|
||||
return rows;
|
||||
@@ -117,11 +120,28 @@ public class TaskListImporter {
|
||||
for (TaskEntryDto entry : task.getEntries()) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("title", entry.getText() == null ? "" : entry.getText());
|
||||
row.put("required", Boolean.TRUE.equals(entry.getRequired()));
|
||||
rows.add(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** {@code choices}-Array (Typ 11) zurück in Zeilen mit Namen ({@code title}). */
|
||||
private List<Map<String, Object>> choiceRows(TaskDto task) {
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
if (task.getChoices() != null && !task.getChoices().isEmpty()) {
|
||||
for (ChoiceDto choice : task.getChoices()) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("title", choice.getTxt() == null ? "" : choice.getTxt());
|
||||
rows.add(row);
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
// Altdaten des früheren Typ 11 (Abhol-/Lieferstatus) liefern die
|
||||
// Optionen als entries; diese als Zeilen übernehmen.
|
||||
return entryRows(task);
|
||||
}
|
||||
|
||||
private Object orDefault(Object value, Object fallback) {
|
||||
return value != null ? value : fallback;
|
||||
}
|
||||
|
||||
@@ -56,6 +56,21 @@ public class TaskListService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut das Task-JSON des aktuellen Canvas als Kontext für den
|
||||
* KI-Assistenten: inklusive der Start-/Abschluss-Markierungen und ohne
|
||||
* Vollständigkeits-Validierung, damit auch unfertige Workflows geändert
|
||||
* werden können.
|
||||
*/
|
||||
public String buildAssistantContext(String drawflowJson, Map<Integer, BlockInstance> instances) {
|
||||
List<TaskDto> tasks = exporter.exportForAssistant(drawflowJson, instances);
|
||||
try {
|
||||
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(tasks);
|
||||
} catch (JsonProcessingException ex) {
|
||||
throw new IllegalStateException("Task-JSON konnte nicht erzeugt werden: " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut aus dem Editor-Zustand das app-konforme Task-Array, wie es die
|
||||
* stadtbote-App verarbeitet (entspricht der {@code tasks}-Liste einer Tour).
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package de.assecutor.tasklisteditor.service;
|
||||
|
||||
import com.anthropic.client.AnthropicClient;
|
||||
import com.anthropic.client.okhttp.AnthropicOkHttpClient;
|
||||
import com.anthropic.models.messages.ContentBlock;
|
||||
import com.anthropic.models.messages.Message;
|
||||
import com.anthropic.models.messages.MessageCreateParams;
|
||||
import com.anthropic.models.messages.ThinkingConfigAdaptive;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import de.assecutor.tasklisteditor.model.BlockType;
|
||||
import de.assecutor.tasklisteditor.model.BlockTypeRegistry;
|
||||
import de.assecutor.tasklisteditor.model.PropertyDefinition;
|
||||
import de.assecutor.tasklisteditor.model.TaskDto;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* KI-Workflow-Assistent: Übersetzt frei formulierte Benutzerwünsche
|
||||
* (Reihenfolge der Elemente und deren Einstellungen) per Claude API in das
|
||||
* {@code tasks}-JSON des Editors. Optional wird der aktuelle Workflow als
|
||||
* Kontext mitgegeben, sodass Claude gezielte Änderungen daran vornimmt statt
|
||||
* neu zu erzeugen. Das Ergebnis läuft über die vorhandene Import-Pipeline
|
||||
* ({@link TaskListImporter}) und baut so den Canvas auf.
|
||||
*/
|
||||
@Service
|
||||
public class WorkflowAssistantService {
|
||||
|
||||
private final BlockTypeRegistry registry;
|
||||
private final String apiKey;
|
||||
private final String model;
|
||||
private final ObjectMapper lenientMapper;
|
||||
|
||||
private volatile AnthropicClient client;
|
||||
|
||||
public WorkflowAssistantService(BlockTypeRegistry registry,
|
||||
@Value("${tasklist.anthropic-api-key:}") String apiKey,
|
||||
@Value("${tasklist.anthropic-model:claude-opus-4-8}") String model) {
|
||||
this.registry = registry;
|
||||
this.apiKey = apiKey == null ? "" : apiKey.trim();
|
||||
this.model = model;
|
||||
this.lenientMapper = new ObjectMapper()
|
||||
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
}
|
||||
|
||||
/** Ergebnis des Assistenten: Workflow-Name plus Tasks in Reihenfolge. */
|
||||
public record WorkflowDraft(String name, List<TaskDto> tasks) {
|
||||
}
|
||||
|
||||
/** Ob der Assistent nutzbar ist (API-Key in der .env hinterlegt). */
|
||||
public boolean isEnabled() {
|
||||
return !apiKey.isBlank();
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt aus dem Benutzerwunsch einen neuen Workflow-Entwurf. Blockiert
|
||||
* bis zur Antwort der Claude API (typisch einige Sekunden bis wenige
|
||||
* Minuten) und sollte daher außerhalb des UI-Threads aufgerufen werden.
|
||||
*
|
||||
* @throws IllegalStateException wenn kein API-Key konfiguriert ist oder
|
||||
* die Antwort nicht verwertbar ist
|
||||
*/
|
||||
public WorkflowDraft generateWorkflow(String wish) {
|
||||
return generateWorkflow(wish, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt oder ändert einen Workflow. Ist {@code currentTasksJson}
|
||||
* gesetzt, erhält Claude den aktuellen Workflow als Kontext, wendet die
|
||||
* beschriebenen Änderungen darauf an und liefert den vollständigen,
|
||||
* aktualisierten Workflow zurück. Blockiert bis zur Antwort der Claude API
|
||||
* und sollte daher außerhalb des UI-Threads aufgerufen werden.
|
||||
*
|
||||
* @param currentName Name des aktuellen Workflows (optional)
|
||||
* @param currentTasksJson Task-JSON des aktuellen Canvas oder {@code null}
|
||||
* für einen neuen Workflow
|
||||
* @throws IllegalStateException wenn kein API-Key konfiguriert ist oder
|
||||
* die Antwort nicht verwertbar ist
|
||||
*/
|
||||
public WorkflowDraft generateWorkflow(String wish, String currentName, String currentTasksJson) {
|
||||
if (!isEnabled()) {
|
||||
throw new IllegalStateException(
|
||||
"Kein Claude-API-Key konfiguriert (ANTHROPIC_API_KEY in der .env-Datei).");
|
||||
}
|
||||
if (wish == null || wish.isBlank()) {
|
||||
throw new IllegalStateException("Bitte einen Workflow-Wunsch eingeben.");
|
||||
}
|
||||
|
||||
MessageCreateParams params = MessageCreateParams.builder()
|
||||
.model(model)
|
||||
.maxTokens(16000L)
|
||||
.thinking(ThinkingConfigAdaptive.builder().build())
|
||||
.system(buildSystemPrompt())
|
||||
.addUserMessage(buildUserMessage(wish, currentName, currentTasksJson))
|
||||
.build();
|
||||
|
||||
Message message = client().messages().create(params);
|
||||
String text = extractText(message);
|
||||
if (text.isBlank()) {
|
||||
throw new IllegalStateException("Die KI hat keine verwertbare Antwort geliefert"
|
||||
+ " (Stop-Grund: " + message.stopReason() + ").");
|
||||
}
|
||||
return parseDraft(text);
|
||||
}
|
||||
|
||||
private AnthropicClient client() {
|
||||
AnthropicClient existing = client;
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
synchronized (this) {
|
||||
if (client == null) {
|
||||
client = AnthropicOkHttpClient.builder()
|
||||
.apiKey(apiKey)
|
||||
.build();
|
||||
}
|
||||
return client;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut die Benutzernachricht: nur der Wunsch (neuer Workflow) oder der
|
||||
* aktuelle Workflow als Kontext plus die gewünschten Änderungen.
|
||||
*/
|
||||
private String buildUserMessage(String wish, String currentName, String currentTasksJson) {
|
||||
if (currentTasksJson == null || currentTasksJson.isBlank()) {
|
||||
return wish;
|
||||
}
|
||||
StringBuilder msg = new StringBuilder("Aktueller Workflow");
|
||||
if (currentName != null && !currentName.isBlank()) {
|
||||
msg.append(" „").append(currentName).append('“');
|
||||
}
|
||||
return msg.append(":\n").append(currentTasksJson)
|
||||
.append("\n\nGewünschte Änderungen:\n").append(wish)
|
||||
.toString();
|
||||
}
|
||||
|
||||
private String extractText(Message message) {
|
||||
StringBuilder text = new StringBuilder();
|
||||
for (ContentBlock block : message.content()) {
|
||||
block.text().ifPresent(t -> text.append(t.text()));
|
||||
}
|
||||
return text.toString().trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parst die Modell-Antwort. Erwartet ein JSON-Objekt
|
||||
* {@code {"name": "...", "tasks": [...]}}; Markdown-Zäune und umgebender
|
||||
* Text werden toleriert.
|
||||
*/
|
||||
private WorkflowDraft parseDraft(String text) {
|
||||
String json = extractJsonObject(text);
|
||||
try {
|
||||
JsonNode root = lenientMapper.readTree(json);
|
||||
JsonNode tasksNode = root.path("tasks");
|
||||
if (!tasksNode.isArray() || tasksNode.isEmpty()) {
|
||||
throw new IllegalStateException("Die KI-Antwort enthält kein tasks-Array.");
|
||||
}
|
||||
List<TaskDto> tasks = new ArrayList<>();
|
||||
for (JsonNode taskNode : tasksNode) {
|
||||
tasks.add(lenientMapper.treeToValue(taskNode, TaskDto.class));
|
||||
}
|
||||
String name = root.path("name").asText("");
|
||||
return new WorkflowDraft(name.isBlank() ? null : name, tasks);
|
||||
} catch (IllegalStateException ex) {
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
throw new IllegalStateException(
|
||||
"Die KI-Antwort konnte nicht als Workflow gelesen werden: " + ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
/** Schneidet das erste JSON-Objekt aus der Antwort (entfernt ```-Zäune u. Ä.). */
|
||||
private String extractJsonObject(String text) {
|
||||
int start = text.indexOf('{');
|
||||
int end = text.lastIndexOf('}');
|
||||
if (start < 0 || end <= start) {
|
||||
throw new IllegalStateException("Die KI-Antwort enthält kein JSON-Objekt.");
|
||||
}
|
||||
return text.substring(start, end + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut die Systemanweisung: beschreibt die verfügbaren Elemente (aus der
|
||||
* {@link BlockTypeRegistry}, inkl. benutzerdefinierter Typen) und das
|
||||
* erwartete JSON-Format.
|
||||
*/
|
||||
private String buildSystemPrompt() {
|
||||
StringBuilder prompt = new StringBuilder();
|
||||
prompt.append("""
|
||||
Du bist der Workflow-Assistent eines grafischen Editors für Auftrags-Workflows
|
||||
(Task-Listen der stadtbote-App). Der Benutzer beschreibt in freier Sprache,
|
||||
welche Elemente sein Workflow in welcher Reihenfolge enthalten soll und wie
|
||||
sie eingestellt sein sollen. Du übersetzt das in ein Task-JSON.
|
||||
|
||||
Es gibt zwei Fälle:
|
||||
- Neuer Workflow: Die Nachricht enthält nur die Wünsche des Benutzers.
|
||||
- Änderung: Der Nachricht ist unter „Aktueller Workflow“ das bestehende
|
||||
Task-JSON vorangestellt. Wende die gewünschten Änderungen darauf an und
|
||||
gib den VOLLSTÄNDIGEN aktualisierten Workflow zurück: Übernimm alle nicht
|
||||
betroffenen Tasks unverändert – inklusive aller vorhandenen Felder, auch
|
||||
hier nicht dokumentierter (z. B. "script") –, und vergib die "s_id"-Werte
|
||||
anschließend lückenlos neu ab 1. Auch der geänderte Workflow muss mit dem
|
||||
Start-Marker (type -1) beginnen und mit dem Abschluss-Marker (type -2)
|
||||
enden – ergänze sie, falls sie im aktuellen Workflow fehlen. Behalte den
|
||||
bisherigen Workflow-Namen bei, sofern der Benutzer keinen neuen verlangt.
|
||||
|
||||
Antworte AUSSCHLIESSLICH mit einem einzigen JSON-Objekt in dieser Form,
|
||||
ohne Markdown-Zäune und ohne erklärenden Text:
|
||||
{"name": "<kurzer, sprechender Workflow-Name>", "tasks": [ <Task-Objekte in Ablauf-Reihenfolge> ]}
|
||||
|
||||
Regeln für die Tasks:
|
||||
- Jeder Task hat "s_id" (fortlaufend ab 1), "type" (Typnummer, siehe Liste)
|
||||
und "topic" (kurze, dem Bearbeiter angezeigte Bezeichnung; nutze die Angaben
|
||||
des Benutzers, sonst die Standardbezeichnung des Typs).
|
||||
- Der erste Task ist immer der Start-Marker (type -1, topic "Start"), der
|
||||
letzte immer der Abschluss-Marker (type -2, topic "Abschluss"), sofern der
|
||||
Benutzer nichts anderes verlangt.
|
||||
- Setze nur die Felder, die für den jeweiligen Typ dokumentiert sind, und nur
|
||||
wenn sie vom Standard abweichen oder der Benutzer sie nennt.
|
||||
- "opt" (boolean) markiert eine insgesamt optionale Aufgabe, "reenter"
|
||||
(boolean) erlaubt erneutes Bearbeiten.
|
||||
- Listenfelder:
|
||||
* "fields": Array aus {"title": "...", "placeholder": "...", "required": true|false}
|
||||
(Text-/Zahlenlisten, Typ 12/13).
|
||||
* "entries": Array aus {"code": <fortlaufend ab 1>, "text": "...", "required": true|false}
|
||||
(Checkbox-Liste, Typ 14).
|
||||
* "choices": Array aus {"txt": "...", "ret": <fortlaufend ab 1>}
|
||||
(Statusauswahl, Typ 11).
|
||||
Kennzeichne Einträge nur dann mit "required": true, wenn der Benutzer sie
|
||||
als Pflicht bezeichnet.
|
||||
- Erfinde keine Elemente, die der Benutzer nicht verlangt hat; wähle bei
|
||||
unklaren Angaben die naheliegendste, einfache Lösung.
|
||||
|
||||
Verfügbare Element-Typen:
|
||||
""");
|
||||
|
||||
for (BlockType type : registry.all()) {
|
||||
if ("script".equals(type.id())) {
|
||||
continue; // Script-Blöcke kann der Assistent nicht sinnvoll konfigurieren.
|
||||
}
|
||||
prompt.append("- type ").append(type.taskType())
|
||||
.append(" „").append(type.label()).append('“');
|
||||
if (type.description() != null && !type.description().isBlank()) {
|
||||
prompt.append(": ").append(type.description());
|
||||
}
|
||||
String fields = fieldDocs(type);
|
||||
if (!fields.isEmpty()) {
|
||||
prompt.append(" Felder: ").append(fields);
|
||||
}
|
||||
prompt.append('\n');
|
||||
}
|
||||
return prompt.toString();
|
||||
}
|
||||
|
||||
private String fieldDocs(BlockType type) {
|
||||
List<String> docs = new ArrayList<>();
|
||||
for (PropertyDefinition def : type.properties()) {
|
||||
String doc = switch (def.type()) {
|
||||
case BOOLEAN -> "\"" + def.id() + "\" (boolean – " + def.label() + ")";
|
||||
case NUMBER -> "\"" + def.id() + "\" (Zahl – " + def.label() + ")";
|
||||
case TEXT, TEXTAREA -> "\"" + def.id() + "\" (Text – " + def.label() + ")";
|
||||
case FIELD_LIST -> "\"fields\" (" + def.label() + ")";
|
||||
case NAME_LIST -> "\"entries\" (" + def.label() + ")";
|
||||
case CHOICE_LIST -> "\"choices\" (" + def.label() + ")";
|
||||
};
|
||||
docs.add(doc);
|
||||
}
|
||||
return String.join(", ", docs);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package de.assecutor.tasklisteditor.view;
|
||||
|
||||
import com.vaadin.flow.component.Component;
|
||||
import com.vaadin.flow.component.UI;
|
||||
import com.vaadin.flow.component.button.Button;
|
||||
import com.vaadin.flow.component.button.ButtonVariant;
|
||||
import com.vaadin.flow.component.checkbox.Checkbox;
|
||||
@@ -18,6 +19,7 @@ import com.vaadin.flow.component.notification.Notification;
|
||||
import com.vaadin.flow.component.orderedlayout.FlexComponent;
|
||||
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
|
||||
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
|
||||
import com.vaadin.flow.component.progressbar.ProgressBar;
|
||||
import com.vaadin.flow.component.textfield.IntegerField;
|
||||
import com.vaadin.flow.component.textfield.TextArea;
|
||||
import com.vaadin.flow.component.textfield.TextField;
|
||||
@@ -33,6 +35,7 @@ import de.assecutor.tasklisteditor.model.BlockType;
|
||||
import de.assecutor.tasklisteditor.model.BlockTypeRegistry;
|
||||
import de.assecutor.tasklisteditor.model.CanvasBlockState;
|
||||
import de.assecutor.tasklisteditor.model.PropertyDefinition;
|
||||
import de.assecutor.tasklisteditor.model.TaskDto;
|
||||
import de.assecutor.tasklisteditor.model.TaskListPayload;
|
||||
import de.assecutor.tasklisteditor.document.CanvasDocument;
|
||||
import de.assecutor.tasklisteditor.service.CanvasService;
|
||||
@@ -41,11 +44,13 @@ import de.assecutor.tasklisteditor.service.ElementSettingsService;
|
||||
import de.assecutor.tasklisteditor.service.PendingImportStore;
|
||||
import de.assecutor.tasklisteditor.service.TaskListImporter;
|
||||
import de.assecutor.tasklisteditor.service.TaskListService;
|
||||
import de.assecutor.tasklisteditor.service.WorkflowAssistantService;
|
||||
import elemental.json.Json;
|
||||
import elemental.json.JsonArray;
|
||||
import elemental.json.JsonObject;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
@@ -59,6 +64,8 @@ import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@Route("")
|
||||
@PageTitle("Workflow Editor")
|
||||
@@ -74,11 +81,25 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
private final CanvasService canvasService;
|
||||
private final CustomTypeService customTypeService;
|
||||
private final ElementSettingsService elementSettingsService;
|
||||
private final WorkflowAssistantService workflowAssistantService;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final NodeEditor nodeEditor;
|
||||
private final Map<Integer, BlockInstance> instances = new HashMap<>();
|
||||
|
||||
/**
|
||||
* Zuletzt vom Canvas entfernte Blöcke. Stellt ein Undo einen Knoten wieder
|
||||
* her, werden seine Einstellungen von hier zurückgeholt (begrenzt, damit
|
||||
* die Session nicht unbegrenzt wächst).
|
||||
*/
|
||||
private final Map<Integer, BlockInstance> removedInstances = new LinkedHashMap<>() {
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Map.Entry<Integer, BlockInstance> eldest) {
|
||||
return size() > 100;
|
||||
}
|
||||
};
|
||||
private Div palettePanel;
|
||||
private String currentListName;
|
||||
private final String appVersion;
|
||||
|
||||
public MainView(BlockTypeRegistry registry,
|
||||
TaskListService taskListService,
|
||||
@@ -87,7 +108,10 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
CanvasService canvasService,
|
||||
CustomTypeService customTypeService,
|
||||
ElementSettingsService elementSettingsService,
|
||||
ObjectMapper objectMapper) {
|
||||
WorkflowAssistantService workflowAssistantService,
|
||||
ObjectMapper objectMapper,
|
||||
@Value("${tasklist.app-version:}") String appVersion) {
|
||||
this.appVersion = appVersion;
|
||||
this.registry = registry;
|
||||
this.taskListService = taskListService;
|
||||
this.taskListImporter = taskListImporter;
|
||||
@@ -95,6 +119,7 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
this.canvasService = canvasService;
|
||||
this.customTypeService = customTypeService;
|
||||
this.elementSettingsService = elementSettingsService;
|
||||
this.workflowAssistantService = workflowAssistantService;
|
||||
this.objectMapper = objectMapper;
|
||||
setSizeFull();
|
||||
setPadding(false);
|
||||
@@ -131,7 +156,52 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
openSettingsDialog(instance);
|
||||
}
|
||||
});
|
||||
nodeEditor.addNodeRemovedListener(e -> instances.remove(e.nodeId()));
|
||||
nodeEditor.addNodeRemovedListener(e -> {
|
||||
BlockInstance removed = instances.remove(e.nodeId());
|
||||
if (removed != null) {
|
||||
removedInstances.put(e.nodeId(), removed);
|
||||
}
|
||||
});
|
||||
nodeEditor.addCanvasRestoredListener(e -> reconcileAfterUndo(e.nodesJson()));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gleicht die serverseitigen BlockInstances nach einem Undo mit den auf dem
|
||||
* Canvas vorhandenen Knoten ab: Verschwundene Knoten wandern in den
|
||||
* Papierkorb, wieder aufgetauchte werden von dort (inkl. ihrer
|
||||
* Einstellungen) wiederhergestellt.
|
||||
*/
|
||||
private void reconcileAfterUndo(String nodesJson) {
|
||||
Map<Integer, String> present = new LinkedHashMap<>();
|
||||
try {
|
||||
JsonNode nodes = objectMapper.readTree(nodesJson);
|
||||
for (JsonNode node : nodes) {
|
||||
present.put(node.path("id").asInt(), node.path("typeId").asText());
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
return;
|
||||
}
|
||||
instances.entrySet().removeIf(entry -> {
|
||||
if (present.containsKey(entry.getKey())) {
|
||||
return false;
|
||||
}
|
||||
removedInstances.put(entry.getKey(), entry.getValue());
|
||||
return true;
|
||||
});
|
||||
present.forEach((id, typeId) -> {
|
||||
if (instances.containsKey(id)) {
|
||||
return;
|
||||
}
|
||||
BlockInstance restored = removedInstances.remove(id);
|
||||
if (restored == null) {
|
||||
BlockType type = registry.find(typeId).orElse(null);
|
||||
if (type == null) {
|
||||
return;
|
||||
}
|
||||
restored = new BlockInstance(id, type);
|
||||
}
|
||||
instances.put(id, restored);
|
||||
});
|
||||
}
|
||||
|
||||
private Component buildHeader() {
|
||||
@@ -146,10 +216,35 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
title.addClassName("tasklist-title");
|
||||
title.getStyle().set("white-space", "nowrap");
|
||||
|
||||
if (appVersion != null && !appVersion.isBlank() && !appVersion.startsWith("@")) {
|
||||
Span version = new Span(" (v" + appVersion + ")");
|
||||
version.getStyle()
|
||||
.set("font-size", "0.7em")
|
||||
.set("color", "var(--lumo-secondary-text-color)")
|
||||
.set("white-space", "nowrap");
|
||||
title.add(version);
|
||||
}
|
||||
|
||||
Button assistant = new Button("KI-Assistent", new Icon(VaadinIcon.MAGIC));
|
||||
assistant.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
|
||||
assistant.setTooltipText("Workflow aus einer Beschreibung erzeugen oder ändern (Claude)");
|
||||
assistant.addClickListener(e -> openAssistantDialog());
|
||||
|
||||
Button undo = new Button("Rückgängig", new Icon(VaadinIcon.ARROW_BACKWARD));
|
||||
undo.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
|
||||
undo.setTooltipText("Letzte Canvas-Änderung zurücknehmen (Strg+Z, max. 10 Schritte)");
|
||||
undo.addClickListener(e -> nodeEditor.undo(undone -> {
|
||||
if (!Boolean.TRUE.equals(undone)) {
|
||||
Notification.show("Nichts zum Rückgängigmachen.");
|
||||
}
|
||||
}));
|
||||
|
||||
Button clear = new Button("Workflow löschen", new Icon(VaadinIcon.TRASH));
|
||||
clear.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
|
||||
clear.addClickListener(e -> {
|
||||
nodeEditor.clear();
|
||||
// In den Papierkorb statt verwerfen: Undo kann das Leeren zurücknehmen.
|
||||
removedInstances.putAll(instances);
|
||||
instances.clear();
|
||||
Notification.show("Canvas geleert");
|
||||
});
|
||||
@@ -162,10 +257,6 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
loadCanvas.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
|
||||
loadCanvas.addClickListener(e -> openLoadCanvasDialog());
|
||||
|
||||
Button appJson = new Button("App-JSON (stadtbote)", new Icon(VaadinIcon.MOBILE));
|
||||
appJson.addThemeVariants(ButtonVariant.LUMO_SUCCESS);
|
||||
appJson.addClickListener(e -> previewAppJson());
|
||||
|
||||
Button export = new Button("JSON erzeugen & speichern", new Icon(VaadinIcon.DOWNLOAD));
|
||||
export.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
|
||||
export.addClickListener(e -> exportTasks());
|
||||
@@ -173,7 +264,7 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
Span spacer = new Span();
|
||||
spacer.getStyle().set("flex", "1");
|
||||
|
||||
header.add(title, spacer, clear, saveCanvas, loadCanvas, appJson, export);
|
||||
header.add(title, spacer, assistant, undo, clear, saveCanvas, loadCanvas, export);
|
||||
return header;
|
||||
}
|
||||
|
||||
@@ -448,7 +539,7 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
private void openBlockDialog(BlockInstance instance) {
|
||||
Dialog dialog = new Dialog();
|
||||
dialog.setHeaderTitle(instance.type().label());
|
||||
dialog.setWidth("440px");
|
||||
dialog.setWidth("585px");
|
||||
|
||||
Paragraph desc = new Paragraph(instance.type().description());
|
||||
desc.addClassName("properties-desc");
|
||||
@@ -719,23 +810,48 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
return box;
|
||||
}
|
||||
case FIELD_LIST -> {
|
||||
return buildRowList(instance, def, current, true);
|
||||
return buildRowList(instance, def, current, true, true);
|
||||
}
|
||||
case NAME_LIST -> {
|
||||
return buildRowList(instance, def, current, false);
|
||||
return buildRowList(instance, def, current, false, true);
|
||||
}
|
||||
case CHOICE_LIST -> {
|
||||
return buildRowList(instance, def, legacyLinesToRows(current), false, false);
|
||||
}
|
||||
}
|
||||
return new Span();
|
||||
}
|
||||
|
||||
/**
|
||||
* Wandelt den früheren Textarea-Wert der Statusauswahl (eine Option pro
|
||||
* Zeile) in die vom Zeilen-Editor erwartete Struktur um. Listen werden
|
||||
* unverändert durchgereicht.
|
||||
*/
|
||||
private Object legacyLinesToRows(Object current) {
|
||||
if (!(current instanceof String s)) {
|
||||
return current;
|
||||
}
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
for (String line : s.split("\\r?\\n")) {
|
||||
String text = line.trim();
|
||||
if (!text.isEmpty()) {
|
||||
Map<String, Object> row = new LinkedHashMap<>();
|
||||
row.put("title", text);
|
||||
rows.add(row);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Editor für eine wiederholbare Liste von Eingabefeldern. Jede Zeile besteht
|
||||
* aus einem Titel und – falls {@code withPlaceholder} – zusätzlich einem
|
||||
* Platzhalter. Der Wert wird als {@code List<Map<String,Object>>} unter der
|
||||
* Platzhalter sowie – falls {@code withRequired} – einer Pflichtfeld-
|
||||
* Checkbox. Der Wert wird als {@code List<Map<String,Object>>} unter der
|
||||
* Property-ID abgelegt (rundläuft über Mongo und Export).
|
||||
*/
|
||||
private Component buildRowList(BlockInstance instance, PropertyDefinition def, Object current,
|
||||
boolean withPlaceholder) {
|
||||
boolean withPlaceholder, boolean withRequired) {
|
||||
List<Map<String, Object>> rows = new ArrayList<>();
|
||||
if (current instanceof List<?> list) {
|
||||
for (Object o : list) {
|
||||
@@ -745,6 +861,11 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
if (withPlaceholder) {
|
||||
row.put("placeholder", m.get("placeholder") == null ? "" : m.get("placeholder").toString());
|
||||
}
|
||||
if (withRequired) {
|
||||
row.put("required", m.get("required") instanceof Boolean b
|
||||
? b
|
||||
: Boolean.parseBoolean(String.valueOf(m.get("required"))));
|
||||
}
|
||||
rows.add(row);
|
||||
}
|
||||
}
|
||||
@@ -798,6 +919,15 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
line.add(placeholder);
|
||||
line.setFlexGrow(1, placeholder);
|
||||
}
|
||||
if (withRequired) {
|
||||
Checkbox required = new Checkbox("Pflicht");
|
||||
required.setValue(Boolean.TRUE.equals(row.get("required")));
|
||||
required.addValueChangeListener(e -> {
|
||||
row.put("required", e.getValue());
|
||||
commit.run();
|
||||
});
|
||||
line.add(required);
|
||||
}
|
||||
line.add(remove);
|
||||
line.setAlignItems(FlexComponent.Alignment.BASELINE);
|
||||
rowsBox.add(line);
|
||||
@@ -812,6 +942,9 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
if (withPlaceholder) {
|
||||
row.put("placeholder", "");
|
||||
}
|
||||
if (withRequired) {
|
||||
row.put("required", false);
|
||||
}
|
||||
rows.add(row);
|
||||
commit.run();
|
||||
render[0].run();
|
||||
@@ -835,11 +968,23 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
|
||||
/** Baut den Canvas aus den per Deep-Link übergebenen Daten auf. */
|
||||
private void loadPayload(TaskListPayload payload) {
|
||||
List<TaskListImporter.ResolvedTask> resolved = taskListImporter.resolve(payload.getTasks());
|
||||
buildCanvasFromTasks(payload.getTasks(), payload.getName(), "aus Deep-Link geladen");
|
||||
}
|
||||
|
||||
/**
|
||||
* Baut den Canvas aus einer Task-Liste neu auf (Knoten in Reihenfolge plus
|
||||
* Verkettung) und legt die zugehörigen {@link BlockInstance}s an. Wird vom
|
||||
* Deep-Link-Import und vom KI-Assistenten genutzt.
|
||||
*/
|
||||
private void buildCanvasFromTasks(List<TaskDto> tasks, String name, String successHint) {
|
||||
List<TaskListImporter.ResolvedTask> resolved = taskListImporter.resolve(tasks);
|
||||
if (resolved.isEmpty()) {
|
||||
Notification.show("Keine verwertbaren Elemente gefunden.");
|
||||
return;
|
||||
}
|
||||
currentListName = payload.getName();
|
||||
if (name != null && !name.isBlank()) {
|
||||
currentListName = name;
|
||||
}
|
||||
|
||||
JsonArray descriptors = Json.createArray();
|
||||
for (int i = 0; i < resolved.size(); i++) {
|
||||
@@ -850,12 +995,15 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
descriptors.set(i, obj);
|
||||
}
|
||||
|
||||
// In den Papierkorb statt verwerfen: Undo kann den Neuaufbau zurücknehmen.
|
||||
removedInstances.putAll(instances);
|
||||
instances.clear();
|
||||
|
||||
nodeEditor.importTasks(descriptors, idsJson -> applyImportedIds(idsJson, resolved));
|
||||
nodeEditor.importTasks(descriptors, idsJson -> applyImportedIds(idsJson, resolved, successHint));
|
||||
}
|
||||
|
||||
private void applyImportedIds(String idsJson, List<TaskListImporter.ResolvedTask> resolved) {
|
||||
private void applyImportedIds(String idsJson, List<TaskListImporter.ResolvedTask> resolved,
|
||||
String successHint) {
|
||||
int[] ids;
|
||||
try {
|
||||
ids = objectMapper.readValue(idsJson, int[].class);
|
||||
@@ -871,7 +1019,141 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
task.values().forEach(instance::set);
|
||||
instances.put(ids[i], instance);
|
||||
}
|
||||
Notification.show(count + " Task(s) aus Deep-Link geladen.");
|
||||
Notification.show(count + " Task(s) " + successHint + ".");
|
||||
}
|
||||
|
||||
// --- KI-Workflow-Assistent (Claude API) ---
|
||||
|
||||
/**
|
||||
* Dialog des KI-Assistenten: Der Benutzer beschreibt in freier Sprache die
|
||||
* gewünschten Elemente, deren Reihenfolge und Einstellungen; Claude
|
||||
* übersetzt das in eine Task-Liste, aus der der Canvas aufgebaut wird.
|
||||
* Liegt bereits ein Workflow auf dem Canvas, wird er als Kontext
|
||||
* mitgegeben und die Beschreibung als Änderungswunsch angewendet.
|
||||
*/
|
||||
private void openAssistantDialog() {
|
||||
if (!workflowAssistantService.isEnabled()) {
|
||||
Notification.show("KI-Assistent nicht verfügbar: Bitte ANTHROPIC_API_KEY "
|
||||
+ "in der .env-Datei hinterlegen und die Anwendung neu starten.");
|
||||
return;
|
||||
}
|
||||
boolean modifying = !instances.isEmpty();
|
||||
|
||||
Dialog dialog = new Dialog();
|
||||
dialog.setHeaderTitle(modifying
|
||||
? "KI-Assistent: Workflow ändern"
|
||||
: "KI-Assistent: Workflow erzeugen");
|
||||
dialog.setWidth("640px");
|
||||
|
||||
Paragraph hint = new Paragraph(modifying
|
||||
? "Beschreibe die gewünschten Änderungen am aktuellen Workflow. Beispiel: "
|
||||
+ "„Nach der Ankunft zwei Pflicht-Fotos einfügen, die Bemerkung optional "
|
||||
+ "machen und die Statusauswahl um ‚Beschädigt‘ ergänzen.“"
|
||||
: "Beschreibe den gewünschten Workflow: welche Elemente "
|
||||
+ "in welcher Reihenfolge und mit welchen Einstellungen. Beispiel: "
|
||||
+ "„Ankunft mit GPS erfassen, dann drei Pflicht-Fotos, Statusauswahl "
|
||||
+ "mit ‚OK‘ und ‚Beschädigt‘, zum Schluss Unterschrift.“");
|
||||
hint.addClassName("properties-desc");
|
||||
|
||||
TextArea wishes = new TextArea(modifying
|
||||
? "Gewünschte Änderungen"
|
||||
: "Wünsche für den Workflow");
|
||||
wishes.setWidthFull();
|
||||
wishes.setMinHeight("160px");
|
||||
wishes.setPlaceholder(modifying
|
||||
? "z. B. Unterschrift ans Ende verschieben, Fotos als Pflicht markieren …"
|
||||
: "z. B. Ankunft melden, danach Fotos (mind. 2), Bemerkung optional …");
|
||||
|
||||
ProgressBar progress = new ProgressBar();
|
||||
progress.setIndeterminate(true);
|
||||
progress.setVisible(false);
|
||||
Span progressLabel = new Span(modifying
|
||||
? "Claude ändert den Workflow – das kann einen Moment dauern …"
|
||||
: "Claude erstellt den Workflow – das kann einen Moment dauern …");
|
||||
progressLabel.setVisible(false);
|
||||
|
||||
VerticalLayout content = new VerticalLayout(hint, wishes, progress, progressLabel);
|
||||
content.setPadding(false);
|
||||
content.setSpacing(true);
|
||||
dialog.add(content);
|
||||
|
||||
Button cancel = new Button("Abbrechen", ev -> dialog.close());
|
||||
cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
|
||||
|
||||
Button generate = new Button(modifying ? "Änderungen anwenden" : "Workflow erzeugen",
|
||||
new Icon(VaadinIcon.MAGIC));
|
||||
generate.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
|
||||
generate.addClickListener(ev -> {
|
||||
String wish = wishes.getValue();
|
||||
if (wish == null || wish.isBlank()) {
|
||||
Notification.show(modifying
|
||||
? "Bitte zuerst die gewünschten Änderungen beschreiben."
|
||||
: "Bitte zuerst die Wünsche für den Workflow beschreiben.");
|
||||
return;
|
||||
}
|
||||
generate.setEnabled(false);
|
||||
wishes.setReadOnly(true);
|
||||
progress.setVisible(true);
|
||||
progressLabel.setVisible(true);
|
||||
|
||||
UI ui = UI.getCurrent();
|
||||
ui.setPollInterval(500);
|
||||
if (modifying) {
|
||||
// Aktuellen Canvas als Task-JSON exportieren und als Kontext mitgeben.
|
||||
nodeEditor.exportGraph(graphJson -> {
|
||||
String currentJson;
|
||||
try {
|
||||
currentJson = taskListService.buildAssistantContext(graphJson, instances);
|
||||
} catch (Exception ex) {
|
||||
ui.setPollInterval(-1);
|
||||
Notification.show("KI-Assistent fehlgeschlagen: " + ex.getMessage());
|
||||
generate.setEnabled(true);
|
||||
wishes.setReadOnly(false);
|
||||
progress.setVisible(false);
|
||||
progressLabel.setVisible(false);
|
||||
return;
|
||||
}
|
||||
runAssistant(dialog, generate, wishes, progress, progressLabel, ui,
|
||||
"per KI-Assistent geändert",
|
||||
() -> workflowAssistantService.generateWorkflow(wish, currentListName, currentJson));
|
||||
});
|
||||
} else {
|
||||
runAssistant(dialog, generate, wishes, progress, progressLabel, ui,
|
||||
"per KI-Assistent erstellt",
|
||||
() -> workflowAssistantService.generateWorkflow(wish));
|
||||
}
|
||||
});
|
||||
|
||||
dialog.getFooter().add(cancel, generate);
|
||||
dialog.open();
|
||||
wishes.focus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Führt den Claude-Aufruf im Hintergrund aus (dauert typisch einige
|
||||
* Sekunden bis Minuten); Polling holt das Ergebnis in die UI. Bei Erfolg
|
||||
* wird der Canvas aus dem gelieferten Entwurf neu aufgebaut.
|
||||
*/
|
||||
private void runAssistant(Dialog dialog, Button generate, TextArea wishes,
|
||||
ProgressBar progress, Span progressLabel, UI ui,
|
||||
String successHint,
|
||||
Supplier<WorkflowAssistantService.WorkflowDraft> call) {
|
||||
CompletableFuture
|
||||
.supplyAsync(call)
|
||||
.whenComplete((draft, error) -> ui.access(() -> {
|
||||
ui.setPollInterval(-1);
|
||||
if (error != null) {
|
||||
Throwable cause = error.getCause() != null ? error.getCause() : error;
|
||||
Notification.show("KI-Assistent fehlgeschlagen: " + cause.getMessage());
|
||||
generate.setEnabled(true);
|
||||
wishes.setReadOnly(false);
|
||||
progress.setVisible(false);
|
||||
progressLabel.setVisible(false);
|
||||
return;
|
||||
}
|
||||
buildCanvasFromTasks(draft.tasks(), draft.name(), successHint);
|
||||
dialog.close();
|
||||
}));
|
||||
}
|
||||
|
||||
// --- Canvas speichern / laden (MongoDB) ---
|
||||
@@ -1054,60 +1336,4 @@ public class MainView extends VerticalLayout implements BeforeEnterObserver {
|
||||
dialog.open();
|
||||
}
|
||||
|
||||
/**
|
||||
* Erzeugt das vollständige, von der stadtbote-App verarbeitbare Job-JSON
|
||||
* (Job → Tour → Tasks) und zeigt es in einem Dialog an.
|
||||
*/
|
||||
private void previewAppJson() {
|
||||
if (instances.isEmpty()) {
|
||||
Notification.show("Es sind keine Funktionsblöcke auf dem Canvas.");
|
||||
return;
|
||||
}
|
||||
nodeEditor.exportGraph(graphJson -> {
|
||||
try {
|
||||
TaskListService.AppJobResult result =
|
||||
taskListService.buildAppJob(currentListName, graphJson, instances);
|
||||
if (result.taskCount() == 0) {
|
||||
Notification.show("Keine app-verarbeitbaren Tasks gefunden.");
|
||||
return;
|
||||
}
|
||||
openAppJsonDialog(result);
|
||||
} catch (Exception ex) {
|
||||
Notification.show("App-JSON fehlgeschlagen: " + ex.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void openAppJsonDialog(TaskListService.AppJobResult result) {
|
||||
Dialog dialog = new Dialog();
|
||||
dialog.setHeaderTitle("App-JSON für stadtbote (" + result.taskCount() + " Tasks)");
|
||||
dialog.setWidth("720px");
|
||||
|
||||
Paragraph hint = new Paragraph("Task-Array, das von der stadtbote-App fehlerfrei "
|
||||
+ "verarbeitet wird. Script-Blöcke werden ausgelassen.");
|
||||
hint.addClassName("properties-desc");
|
||||
|
||||
TextArea json = new TextArea("App-JSON (tasks-Array)");
|
||||
json.setWidthFull();
|
||||
json.setHeight("420px");
|
||||
json.setReadOnly(true);
|
||||
json.setValue(result.json());
|
||||
|
||||
VerticalLayout content = new VerticalLayout(hint, json);
|
||||
content.setPadding(false);
|
||||
content.setSpacing(true);
|
||||
dialog.add(content);
|
||||
|
||||
Button copy = new Button("In Zwischenablage kopieren", new Icon(VaadinIcon.COPY), ev -> {
|
||||
getElement().executeJs("navigator.clipboard.writeText($0)", result.json());
|
||||
Notification.show("JSON in die Zwischenablage kopiert.");
|
||||
});
|
||||
copy.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
|
||||
|
||||
Button close = new Button("Schließen", ev -> dialog.close());
|
||||
close.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
|
||||
|
||||
dialog.getFooter().add(close, copy);
|
||||
dialog.open();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
server.port=8080
|
||||
|
||||
# Anwendungsversion: wird beim Build per Maven-Resource-Filtering
|
||||
# (spring-boot-starter-parent, @...@-Delimiter) aus der pom.xml gefüllt.
|
||||
tasklist.app-version=@project.version@
|
||||
|
||||
vaadin.launch-browser=true
|
||||
vaadin.allowed-packages=de.assecutor.tasklisteditor
|
||||
|
||||
@@ -26,6 +30,12 @@ management.health.mongo.enabled=false
|
||||
# Wird per .env (HIDE_SCRIPT_BLOCK) gesteuert.
|
||||
tasklist.hide-script-block=${HIDE_SCRIPT_BLOCK:false}
|
||||
|
||||
# --- KI-Workflow-Assistent (Claude API) --------------------------------------
|
||||
# API-Key und Modell kommen aus der .env-Datei (ANTHROPIC_API_KEY,
|
||||
# ANTHROPIC_MODEL). Ohne Key ist der Assistent im Editor deaktiviert.
|
||||
tasklist.anthropic-api-key=${ANTHROPIC_API_KEY:}
|
||||
tasklist.anthropic-model=${ANTHROPIC_MODEL:claude-opus-4-8}
|
||||
|
||||
# --- Collections je Element-Typ ---------------------------------------------
|
||||
# Einstellungen der einzelnen Elemente werden beim Canvas-Speichern zusätzlich
|
||||
# je Element-Typ in eine eigene Collection geschrieben. Namen aus der .env
|
||||
|
||||
Reference in New Issue
Block a user