Compare commits

...

13 Commits

Author SHA1 Message Date
525e775d1c build: Maven Wrapper hinzugefügt und docker_push.sh an Projekt angepasst
- mvnw/.mvn per 'mvn -N wrapper:wrapper' erzeugt (docker_push.sh setzt den Wrapper voraus)
- JAR-Name in docker_push.sh von votianlt auf tasklist-editor korrigiert
- pom-Version wird nur noch einmal aufgelöst; wirkungsloses -Drevision entfernt

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:53:28 +02:00
a92eaf66cf feat: KI-Funktionalität per .env-Schalter AI_ENABLED abschaltbar (Standard: aus)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 10:48:09 +02:00
155ccd016e feat: KI-Workflow-Assistent (Claude API) zum Erzeugen und Ändern von Workflows
- Neuer WorkflowAssistantService: übersetzt frei formulierte Wünsche per
  Claude API in das Task-JSON des Editors (Anthropic-SDK, Key aus .env)
- Bestehende Workflows änderbar: aktueller Canvas wird als Kontext
  mitgegeben (inkl. Start-/Abschluss-Marker, ohne Validierung), Claude
  wendet die Änderungen an und liefert den vollständigen Workflow zurück
- Assistenten-Dialog passt sich an (Erzeugen vs. Ändern), Claude-Aufruf
  läuft im Hintergrund mit UI-Polling
- Canvas-Neuaufbau legt alte Blöcke in den Undo-Papierkorb (Strg+Z)
- Button "App-JSON (stadtbote)" samt Vorschau-Dialog entfernt
- Version 0.9.2

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 10:19:55 +02:00
d0b2373cc1 feat: Undo (max. 10 Schritte), Pflichtfelder je Listeneintrag und Statusauswahl als Zeilen-Editor
- Canvas-Undo über Schnappschuss-Historie (Strg+Z + Header-Button); Server
  gleicht BlockInstances nach Undo ab und stellt Einstellungen gelöschter
  Blöcke aus einem Papierkorb wieder her
- Element-Einstellungsdialog um 33% vergrößert (440px -> 585px)
- Listen von Texten/Zahlen/Checkboxen: Pflicht-Checkbox je Eintrag statt
  übergreifender "Optionale Aufgabe"; required wird im JSON (fields/entries)
  exportiert und beim Deep-Link-Import wiederhergestellt
- Statusauswahl erfasst Optionen als einzelne Zeilen (CHOICE_LIST) statt
  Textarea; Altdaten (Text bzw. entries) werden weiter unterstützt
- Titeländerungen werden im Graph-HTML nachgezogen (überleben Export/Laden)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-06 08:03:39 +02:00
72508a60bf fix: Drawflows Lösch-"x" beim Rechtsklick unterdrücken
Rechts dient nur zum Verschieben von Knoten bzw. der Ansicht; das
contextmenu-Event wird in der Capture-Phase gestoppt, bevor Drawflow
den Lösch-Button am selektierten Knoten einblendet.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 13:10:23 +02:00
00f7b4f1ce fix: Drop-Position bei Zoom korrigiert und Canvas-Panning mit rechter Maustaste
- Drop- und Klickkoordinaten über das transformierte precanvas-Rect
  umrechnen (berücksichtigt transform-origin in der Canvas-Mitte)
- Greif-Offset in Canvas-Einheiten abziehen, damit der Knoten in jeder
  Zoomstufe unter dem Mauszeiger erscheint
- Rechtsklick auf freien Canvas verschiebt jetzt die gesamte Ansicht

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 11:46:36 +02:00
5f85074653 feat: App-Version aus pom.xml im Header anzeigen
- Versionsnummer neben "Workflow Editor" in Klammern und kleinerer Schrift
- tasklist.app-version per Maven-Resource-Filtering (@project.version@) gefüllt
- @Value-Injection in MainView; Anzeige nur bei real gefülltem Wert

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 09:49:18 +02:00
cdfc779bc8 feat: Palette-Layout überarbeitet und Start/Abschluss als reguläre Elemente
- "Eigenen Typ anlegen" als blauer Primary-Button (wie Export-Button)
- Button und Trenner fest zwischen Standard- und Custom-Typen platziert
- Header vereinfacht: Untertitel entfernt, Titel umbruchfrei
- Start/Abschluss-Beschreibungen ohne "virtuell/nicht exportiert"

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 17:01:46 +02:00
23b403711d feat: vollständige Verdrahtung erzwingen und unvollständige Elemente markieren
- Workflow-Validierung verschärft: jedes Element muss alle vorhandenen Ein- und Ausgänge verbunden haben (Start nur Ausgang, Abschluss nur Eingang)
- Unvollständig verdrahtete Elemente werden im Editor live hellrot markiert
- Fix: tsconfig ignoreDeprecations zurück auf "5.0" (TS 5.7.3 lehnt "6.0" ab -> Vite-Build brach ab)
- MainView: Beschriftungen auf "Workflow" angepasst

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 16:07:44 +02:00
cf9c73635b feat: Listen-Elemente, virtuelle Start/Abschluss-Blöcke und Workflow-Validierung
- Neue Aufgabentypen: Text-/Zahlen-Liste (fields) und Checkbox-Liste (entries); Export/Import um fields und choices erweitert
- Typ-spezifische Element-Einstellungen in MongoDB (ElementSettingsService/-Document, ElementCollectionProperties)
- Virtuelle Start-/Abschluss-Elemente (nur zur Darstellung, nicht exportiert); keine Einstellungen; Export erzwingt vorhandenes und verdrahtetes Start- und Abschluss-Element
- Node-Editor: nur eine Verbindung je Ausgang (Start des Drags unterbunden)
- Script-Block korrekt aus dem App-JSON gefiltert (Typ 0)
- Fixes: tsconfig ignoreDeprecations 6.0; JDT-Null-Analyse (Method-Referenzen zu Lambdas)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 12:57:52 +02:00
7d5fd3b590 feat: benutzerdefinierte Typen, Typ-Nummerierung und Linien löschen
- Feste Element-Typen fortlaufend nummeriert (1–8), Script = 0;
  Alt-Daten-Mapping im Importer entfernt
- Benutzerdefinierte Typen ab Nummer 1000 über Dialog anlegen
  (Basis-Typ-Auswahl + Datenerfassung) und wieder löschen
- Eigene Typen vollständig in MongoDB speichern und beim Start laden
  (CustomTypeDocument/-Repository/-Service, eindeutige Typnummer)
- Palette: Trenner und Markierung für benutzerdefinierte Typen,
  Papierkorb-Icon zum Löschen, robusterer Textumbruch
- Verbindungslinien im Canvas selektierbar und per Entf löschbar
  (korrekter Drawflow-Klassenselektor node_in_node-, Näherungsauswahl)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 09:49:51 +02:00
efca20c5f3 feat: hindernis-bewusste Linienführung in den Node-Editoren
Verbindungslinien meiden nach Möglichkeit andere Kacheln. Kreuzt die direkte
Kurve eine Kachel (bzw. bei Rückwärtskanten die Quell-/Zielkachel), wird die
Linie über eine freie Spalte seitlich an den Kacheln vorbei umgeleitet und mit
abgerundeten Ecken gezeichnet. Treffererkennung tastet den tatsächlichen
SVG-Pfad ab; die Führung wird bei nodeMoved dynamisch neu berechnet.

- node-editor.js: vertikale Port-Ausrichtung (Ausgang unten -> Eingang oben)
- script-editor.js: horizontale Port-Ausrichtung (Ausgang rechts -> Eingang links)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 14:03:54 +02:00
67c92bceb3 feat: grafischer Script-/Logik-Block für Aufgaben
Neuer "Script"-Blocktyp, dessen Logik (Konstanten, Variablen, Vergleiche,
Wenn/Dann, UND/ODER/NICHT, Ergebnis/Ausgang) in einem eigenen Drawflow-Canvas
zusammengesteckt wird.

- ScriptEditor-Komponente + script-editor.js (eigener Logik-Canvas mit
  horizontaler Kurvenführung, Raster-Snapping, Drag&Drop der Operatoren)
- Script-Dialog in MainView: verbundene Eingangselemente werden als Variablen
  angeboten, Anzahl der Ausgänge des Knotens richtet sich nach den Ausgang-Knoten
- Knoten-Aktivierung (Zahnrad/Doppelklick) über NodeActivatedEvent und
  setNodeOutputs im NodeEditor
- script-Feld in TaskDto + Export des Logik-Graphen im TaskListExporter
- Verbindungen werden beim Wiederöffnen des Dialogs zuverlässig neu gezeichnet
  (Neuberechnung nach Stabilisierung des Dialog-Layouts)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 10:38:03 +02:00
32 changed files with 4571 additions and 144 deletions

View File

@@ -15,3 +15,42 @@ MONGODB_COLLECTION=tasks_json
# Collection, in der die Canvas-Stände (Layout + Werte) gespeichert werden: # Collection, in der die Canvas-Stände (Layout + Werte) gespeichert werden:
MONGODB_CANVAS_COLLECTION=canvas_layouts MONGODB_CANVAS_COLLECTION=canvas_layouts
# Collection, in der die benutzerdefinierten Typen gespeichert werden:
MONGODB_CUSTOM_TYPE_COLLECTION=custom_types
# --- Collections je Element-Typ ---------------------------------------------
# Beim Speichern eines Canvas werden die Einstellungen jedes platzierten
# Elements zusätzlich je Typ in eine eigene Collection geschrieben.
# (Benutzerdefinierte Typen nutzen die Collection ihres Basistyps.)
MONGODB_ELEMENT_ARRIVAL_COLLECTION=element_arrival
MONGODB_ELEMENT_SIGNATURE_COLLECTION=element_signature
MONGODB_ELEMENT_PHOTOS_COLLECTION=element_photos
MONGODB_ELEMENT_RECEIPT_GIVER_COLLECTION=element_receipt_giver
MONGODB_ELEMENT_REMARK_COLLECTION=element_remark
MONGODB_ELEMENT_COMMISSION_NUMBER_COLLECTION=element_commission_number
MONGODB_ELEMENT_CHECKBOX_COLLECTION=element_checkbox
MONGODB_ELEMENT_BARCODE_COLLECTION=element_barcode
MONGODB_ELEMENT_STATUS_SELECTION_COLLECTION=element_status_selection
MONGODB_ELEMENT_TEXT_LIST_COLLECTION=element_text_list
MONGODB_ELEMENT_NUMBER_LIST_COLLECTION=element_number_list
MONGODB_ELEMENT_CHECKBOX_LIST_COLLECTION=element_checkbox_list
MONGODB_ELEMENT_SCRIPT_COLLECTION=element_script
# Script-Block (grafisches Logik-Element) ausblenden:
# true = Script-Element wird im Editor nicht angezeigt
# false = Script-Element ist verfügbar (Standard)
HIDE_SCRIPT_BLOCK=false
# --- KI-Workflow-Assistent ---------------------------------------------------
# KI-Funktionalität ein-/ausschalten:
# true = KI-Assistent ist im Editor verfügbar
# false = KI-Assistent ist deaktiviert (Standard)
AI_ENABLED=false
# API-Key für die Claude API (https://platform.claude.com/settings/keys).
# Ohne Key ist der KI-Assistent im Editor deaktiviert.
ANTHROPIC_API_KEY=
# Verwendetes Claude-Modell (Standard: claude-opus-4-8):
#ANTHROPIC_MODEL=claude-opus-4-8

3
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.11/apache-maven-3.9.11-bin.zip

83
docker_push.sh Executable file
View File

@@ -0,0 +1,83 @@
#!/usr/bin/env bash
set -euo pipefail
readonly SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
readonly REGISTRY_IMAGE="registry.assecutor.org/ait"
readonly BACKEND_DIR="${SCRIPT_DIR}"
usage() {
cat <<'EOF'
Verwendung:
./docker_push.sh [x.y.z]
Beispiel:
./docker_push.sh 0.9.13
./docker_push.sh
Voraussetzungen:
- Docker Buildx ist installiert
- Login zur Registry wurde bereits ausgeführt:
docker login registry.assecutor.org
Ohne Versionsargument wird automatisch die Version aus der pom.xml verwendet.
EOF
}
fail() {
echo "Fehler: $*" >&2
exit 1
}
require_command() {
command -v "$1" >/dev/null 2>&1 || fail "'$1' wurde nicht gefunden."
}
resolve_pom_version() {
[[ -x "${BACKEND_DIR}/mvnw" ]] || fail "'${BACKEND_DIR}/mvnw' wurde nicht gefunden oder ist nicht ausführbar."
local version
version="$(
cd "${BACKEND_DIR}" && ./mvnw -q -DforceStdout help:evaluate -Dexpression=project.version \
| awk 'NF { last = $0 } END { print last }'
)"
[[ -n "${version}" ]] || fail "Version konnte nicht aus der pom.xml ermittelt werden."
echo "${version}"
}
if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
usage
exit 0
fi
POM_VERSION="$(resolve_pom_version)"
VERSION="${1:-${POM_VERSION}}"
if [[ ! "${VERSION}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
fail "Versionsnummer muss das Format x.y.z haben."
fi
require_command docker
docker buildx version >/dev/null 2>&1 || fail "Docker Buildx ist nicht verfügbar."
cd "${SCRIPT_DIR}"
echo "Verwende Release-Version ${VERSION}."
echo "Baue Production-JAR für Version ${VERSION} ..."
(cd "${BACKEND_DIR}" && ./mvnw -Pproduction -DskipTests package)
JAR_FILE_REL="target/tasklist-editor-${POM_VERSION}.jar"
JAR_FILE_ABS="${BACKEND_DIR}/${JAR_FILE_REL}"
[[ -f "${JAR_FILE_ABS}" ]] || fail "Release-JAR wurde nicht gefunden: ${JAR_FILE_ABS}"
echo "Pushe Image ${REGISTRY_IMAGE}:${VERSION} ..."
docker buildx build \
--platform linux/amd64 \
-f "${BACKEND_DIR}/Dockerfile" \
--build-arg "JAR_FILE=${JAR_FILE_REL}" \
-t "${REGISTRY_IMAGE}:${VERSION}" \
--push \
"${BACKEND_DIR}"
echo "Fertig: ${REGISTRY_IMAGE}:${VERSION}"

295
mvnw vendored Executable file
View File

@@ -0,0 +1,295 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.4
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
if [ -n "${JAVA_HOME-}" ]; then
if [ -x "$JAVA_HOME/jre/sh/java" ]; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
scriptDir="$(dirname "$0")"
scriptName="$(basename "$0")"
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
# Find the actual extracted directory name (handles snapshots where filename != directory name)
actualDistributionDir=""
# First try the expected directory name (for regular distributions)
if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then
if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then
actualDistributionDir="$distributionUrlNameMain"
fi
fi
# If not found, search for any directory with the Maven executable (for snapshots)
if [ -z "$actualDistributionDir" ]; then
# enable globbing to iterate over items
set +f
for dir in "$TMP_DOWNLOAD_DIR"/*; do
if [ -d "$dir" ]; then
if [ -f "$dir/bin/$MVN_CMD" ]; then
actualDistributionDir="$(basename "$dir")"
break
fi
fi
done
set -f
fi
if [ -z "$actualDistributionDir" ]; then
verbose "Contents of $TMP_DOWNLOAD_DIR:"
verbose "$(ls -la "$TMP_DOWNLOAD_DIR")"
die "Could not find Maven distribution directory in extracted archive"
fi
verbose "Found extracted Maven distribution directory: $actualDistributionDir"
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

189
mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,189 @@
<# : batch portion
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Apache Maven Wrapper startup batch script, version 3.3.4
@REM
@REM Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_M2_PATH = "$HOME/.m2"
if ($env:MAVEN_USER_HOME) {
$MAVEN_M2_PATH = "$env:MAVEN_USER_HOME"
}
if (-not (Test-Path -Path $MAVEN_M2_PATH)) {
New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null
}
$MAVEN_WRAPPER_DISTS = $null
if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) {
$MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists"
} else {
$MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists"
}
$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain"
$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
# Find the actual extracted directory name (handles snapshots where filename != directory name)
$actualDistributionDir = ""
# First try the expected directory name (for regular distributions)
$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain"
$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD"
if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) {
$actualDistributionDir = $distributionUrlNameMain
}
# If not found, search for any directory with the Maven executable (for snapshots)
if (!$actualDistributionDir) {
Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object {
$testPath = Join-Path $_.FullName "bin/$MVN_CMD"
if (Test-Path -Path $testPath -PathType Leaf) {
$actualDistributionDir = $_.Name
}
}
}
if (!$actualDistributionDir) {
Write-Error "Could not find Maven distribution directory in extracted archive"
}
Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir"
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

View File

@@ -13,7 +13,7 @@
<groupId>de.assecutor</groupId> <groupId>de.assecutor</groupId>
<artifactId>tasklist-editor</artifactId> <artifactId>tasklist-editor</artifactId>
<version>0.2.0</version> <version>0.9.2</version>
<name>TaskList Editor</name> <name>TaskList Editor</name>
<description>n8n-inspired editor for task list workflows</description> <description>n8n-inspired editor for task list workflows</description>
@@ -57,6 +57,13 @@
<version>4.0.0</version> <version>4.0.0</version>
</dependency> </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> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId> <artifactId>spring-boot-devtools</artifactId>

View File

@@ -1,36 +1,250 @@
import Drawflow from 'drawflow'; import Drawflow from 'drawflow';
import 'drawflow/dist/drawflow.min.css'; import 'drawflow/dist/drawflow.min.css';
function customCurvature(sx, sy, ex, ey) { // Senkrechter Stub, mit dem jede Linie aus dem Ausgang austritt bzw.
// senkrecht in den Eingang des Ziels eintritt, bevor sie abbiegt.
const EXIT_STUB = 5;
// Greif-Offset (in Bildschirm-Pixeln) zwischen Mauszeiger und linker oberer
// Ecke des gezogenen Palette-Elements. Wird beim Drop abgezogen, damit der
// Knoten an seiner gezogenen Position liegt statt mit der Ecke an der Maus.
let dragGrabOffset = { x: 0, y: 0 };
function verticalCurvature(sx, sy, ex, ey) {
const dx = ex - sx; const dx = ex - sx;
const dy = ey - sy;
const adyt = Math.abs(dy);
const minOffset = 40; const minOffset = 40;
if (dy >= -8) { // Punkte nach dem Austritts- bzw. vor dem Eintritts-Stub.
const offset = Math.max(adyt * 0.5, minOffset); const sy2 = sy + EXIT_STUB;
const c1x = sx + dx * 0.5; const ey2 = ey - EXIT_STUB;
const c1y = sy + offset;
const c2x = ex; if (ey - sy >= -8) {
const c2y = ey - offset; const offset = Math.max(Math.abs(ey2 - sy2) * 0.5, minOffset);
return ` M ${sx} ${sy} C ${c1x} ${c1y} ${c2x} ${c2y} ${ex} ${ey}`; const c1x = sx; // Tangente bleibt senkrecht zum Austritts-Stub
const c1y = sy2 + offset;
const c2x = ex; // Tangente bleibt senkrecht zum Eintritts-Stub
const c2y = ey2 - offset;
return ` M ${sx} ${sy} L ${sx} ${sy2} C ${c1x} ${c1y} ${c2x} ${c2y} ${ex} ${ey2} L ${ex} ${ey}`;
} }
const loopOffset = adyt * 0.5 + 80; const loopOffset = Math.abs(ey2 - sy2) * 0.5 + 80;
const sign = Math.sign(dx) || 1; const sign = Math.sign(dx) || 1;
const c1x = sx + sign * 60; const c1x = sx; // Tangente bleibt senkrecht zum Austritts-Stub
const c1y = sy + loopOffset; const c1y = sy2 + loopOffset;
const c2x = ex - sign * 60; const c2x = ex - sign * 60;
const c2y = ey - loopOffset; const c2y = ey2 - loopOffset;
return ` M ${sx} ${sy} C ${c1x} ${c1y} ${c2x} ${c2y} ${ex} ${ey}`; return ` M ${sx} ${sy} L ${sx} ${sy2} C ${c1x} ${c1y} ${c2x} ${c2y} ${ex} ${ey2} L ${ex} ${ey}`;
}
// --- Hindernis-bewusste Linienführung -------------------------------------
// Ports liegen oben (Eingang) und unten (Ausgang). Damit Linien nach
// Möglichkeit nicht über andere Kacheln (oder bei Rückwärtskanten über Quell-/
// Zielkachel) laufen, werden kreuzende Verbindungen seitlich an den Kacheln
// vorbei über eine freie Spalte umgeleitet.
const ROUTE_STUB = 16; // senkrechte Aus-/Eintrittsstrecke an den Ports
const ROUTE_PAD = 18; // Sicherheitsabstand um jede Kachel
const ROUTE_RADIUS = 14; // Eckenradius der Umleitung
// Alle Knoten-Rechtecke (Canvas-Koordinaten, inkl. Sicherheitsabstand).
function nodeRects(state) {
const rects = [];
state.container.querySelectorAll('.drawflow-node').forEach(el => {
const left = parseFloat(el.style.left) || 0;
const top = parseFloat(el.style.top) || 0;
const w = el.offsetWidth || 0;
const h = el.offsetHeight || 0;
if (!w || !h) return;
rects.push({
left: left - ROUTE_PAD, top: top - ROUTE_PAD,
right: left + w + ROUTE_PAD, bottom: top + h + ROUTE_PAD
});
});
return rects;
}
// Rechtecke ohne die Quell-/Zielkachel (die die Endpunkte enthalten).
function withoutEndpointRects(rects, sx, sy, ex, ey) {
return rects.filter(r => {
const hasStart = sx >= r.left && sx <= r.right && sy >= r.top && sy <= r.bottom;
const hasEnd = ex >= r.left && ex <= r.right && ey >= r.top && ey <= r.bottom;
return !hasStart && !hasEnd;
});
}
function pointInAnyRect(x, y, rects) {
return rects.some(r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom);
}
// Tastet einen beliebigen SVG-Pfad ab und prüft, ob er über eine Kachel läuft.
function pathHits(d, rects) {
if (!rects.length) return false;
const p = document.createElementNS('http://www.w3.org/2000/svg', 'path');
p.setAttribute('d', d);
let total = 0;
try { total = p.getTotalLength(); } catch (e) { return false; }
if (!total) return false;
const steps = Math.max(16, Math.min(120, Math.round(total / 10)));
for (let i = 1; i < steps; i++) {
const pt = p.getPointAtLength((i / steps) * total);
if (pointInAnyRect(pt.x, pt.y, rects)) return true;
}
return false;
}
// Treffer-Test für achsenparallele Wegpunkte (Segment-BBox == Segment).
function segmentsHit(points, rects) {
for (let i = 0; i < points.length - 1; i++) {
const a = points[i], b = points[i + 1];
const left = Math.min(a.x, b.x), right = Math.max(a.x, b.x);
const top = Math.min(a.y, b.y), bottom = Math.max(a.y, b.y);
if (rects.some(r => right >= r.left && left <= r.right && bottom >= r.top && top <= r.bottom)) {
return true;
}
}
return false;
}
// Wegpunkte: aus dem Ausgang nach unten, über eine freie Spalte (channelX)
// und von oben in den Eingang.
function channelWaypoints(sx, sy, ex, ey, channelX) {
const ay = sy + ROUTE_STUB;
const by = ey - ROUTE_STUB;
return [
{ x: sx, y: sy }, { x: sx, y: ay }, { x: channelX, y: ay },
{ x: channelX, y: by }, { x: ex, y: by }, { x: ex, y: ey }
];
}
// Glatter Pfad mit abgerundeten Ecken durch achsenparallele Wegpunkte.
function roundedPath(pts, radius) {
const points = [];
for (const p of pts) {
const last = points[points.length - 1];
if (!last || Math.abs(last.x - p.x) > 0.5 || Math.abs(last.y - p.y) > 0.5) points.push(p);
}
if (points.length < 2) return '';
if (points.length === 2) {
return `M ${points[0].x} ${points[0].y} L ${points[1].x} ${points[1].y}`;
}
let d = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length - 1; i++) {
const p0 = points[i - 1], p1 = points[i], p2 = points[i + 1];
const v1x = p1.x - p0.x, v1y = p1.y - p0.y;
const v2x = p2.x - p1.x, v2y = p2.y - p1.y;
const len1 = Math.hypot(v1x, v1y) || 1;
const len2 = Math.hypot(v2x, v2y) || 1;
const rr = Math.min(radius, len1 / 2, len2 / 2);
const s1x = p1.x - (v1x / len1) * rr, s1y = p1.y - (v1y / len1) * rr;
const e1x = p1.x + (v2x / len2) * rr, e1y = p1.y + (v2y / len2) * rr;
d += ` L ${s1x} ${s1y} Q ${p1.x} ${p1.y} ${e1x} ${e1y}`;
}
const last = points[points.length - 1];
d += ` L ${last.x} ${last.y}`;
return d;
}
// Liefert den SVG-Pfad einer Verbindung direkt, falls frei, sonst umgeleitet.
function routeConnection(state, sx, sy, ex, ey) {
const direct = verticalCurvature(sx, sy, ex, ey);
const all = nodeRects(state);
const others = withoutEndpointRects(all, sx, sy, ex, ey);
// Klare Vorwärtskante ohne fremde Kachel im Weg -> bisherige Kurve behalten.
const isBackward = ey < sy + 2 * ROUTE_STUB;
if (!isBackward && !pathHits(direct, others)) return direct;
// Bei Rückwärtskanten auch um Quell-/Zielkachel herum, bei Vorwärtskanten
// nur um fremde Kacheln.
const candidates = isBackward ? all : others;
const spanTop = Math.min(sy, ey) - ROUTE_STUB;
const spanBottom = Math.max(sy, ey) + ROUTE_STUB;
const blockers = candidates.filter(r => r.bottom > spanTop && r.top < spanBottom);
if (!blockers.length) return direct;
const ref = (sx + ex) / 2;
const leftX = Math.min(...blockers.map(r => r.left)) - ROUTE_PAD;
const rightX = Math.max(...blockers.map(r => r.right)) + ROUTE_PAD;
const first = Math.abs(leftX - ref) <= Math.abs(rightX - ref) ? leftX : rightX;
const second = first === leftX ? rightX : leftX;
let wp = channelWaypoints(sx, sy, ex, ey, first);
if (segmentsHit(wp, others)) {
const alt = channelWaypoints(sx, sy, ex, ey, second);
if (!segmentsHit(alt, others)) wp = alt;
}
return roundedPath(wp, ROUTE_RADIUS);
} }
if (Drawflow && Drawflow.prototype) { if (Drawflow && Drawflow.prototype) {
Drawflow.prototype.createCurvature = customCurvature; Drawflow.prototype.createCurvature = verticalCurvature;
} }
const editors = new WeakMap(); 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) { if (!window.__taskListEditorDragInit) {
window.__taskListEditorDragInit = true; window.__taskListEditorDragInit = true;
document.addEventListener('dragstart', e => { document.addEventListener('dragstart', e => {
@@ -38,10 +252,40 @@ if (!window.__taskListEditorDragInit) {
if (target && e.dataTransfer) { if (target && e.dataTransfer) {
e.dataTransfer.setData('application/x-blocktype', target.dataset.blocktype); e.dataTransfer.setData('application/x-blocktype', target.dataset.blocktype);
e.dataTransfer.effectAllowed = 'copy'; e.dataTransfer.effectAllowed = 'copy';
const r = target.getBoundingClientRect();
dragGrabOffset = { x: e.clientX - r.left, y: e.clientY - r.top };
} }
}, true); }, true);
} }
/**
* Markiert alle Knoten, deren Ein- oder Ausgänge nicht vollständig verdrahtet
* sind, mit der CSS-Klasse {@code node-incomplete} (hellroter Hintergrund).
* Start-Knoten (kein Eingang) und Abschluss-Knoten (kein Ausgang) werden anhand
* ihrer tatsächlich vorhandenen Ports bewertet.
*/
function refreshValidity(state) {
if (!state) return;
const editor = state.editor;
const data = editor.drawflow.drawflow[editor.module].data;
for (const id in data) {
const node = data[id];
const incomplete = hasOpenPort(node.inputs) || hasOpenPort(node.outputs);
const el = state.container.querySelector('#node-' + id);
if (el) el.classList.toggle('node-incomplete', incomplete);
}
}
/** Liefert true, wenn mindestens einer der vorhandenen Ports keine Verbindung hat. */
function hasOpenPort(ports) {
if (!ports) return false;
for (const key in ports) {
const connections = ports[key] && ports[key].connections;
if (!connections || connections.length === 0) return true;
}
return false;
}
function buildNodeHtml(label, color) { function buildNodeHtml(label, color) {
const safe = String(label).replace(/[<>&"']/g, c => ({ const safe = String(label).replace(/[<>&"']/g, c => ({
'<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;'
@@ -49,6 +293,9 @@ function buildNodeHtml(label, color) {
return ` return `
<div class="task-node" data-color="${color}"> <div class="task-node" data-color="${color}">
<div class="task-node-header" style="background:${color}"></div> <div class="task-node-header" style="background:${color}"></div>
<div class="task-node-gear" title="Einstellungen">
<svg viewBox="0 0 24 24" fill="currentColor"><path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96a7.03 7.03 0 0 0-1.62-.94l-.36-2.54a.48.48 0 0 0-.48-.41h-3.84a.48.48 0 0 0-.48.41l-.36 2.54c-.59.24-1.13.56-1.62.94l-2.39-.96a.48.48 0 0 0-.59.22L2.74 8.87c-.12.21-.07.49.12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.48-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32a.49.49 0 0 0-.12-.61l-2.03-1.58zM12 15.6A3.6 3.6 0 1 1 12 8.4a3.6 3.6 0 0 1 0 7.2z"/></svg>
</div>
<div class="task-node-body"> <div class="task-node-body">
<div class="task-node-title">${safe}</div> <div class="task-node-title">${safe}</div>
</div> </div>
@@ -73,15 +320,26 @@ function attach(host) {
editor.reroute = true; editor.reroute = true;
editor.reroute_fix_curvature = true; editor.reroute_fix_curvature = true;
editor.curvature = 0.5; editor.curvature = 0.5;
editor.createCurvature = customCurvature;
editor.start(); editor.start();
const state = { const state = {
editor, editor,
container, container,
registry: new Map() host,
registry: new Map(),
history: [],
undoSuppressed: false,
undoScheduled: false
}; };
editors.set(host, state); editors.set(host, state);
resetHistory(state);
// Hindernis-bewusste Linienführung. Reroute-Teilsegmente
// (type != 'openclose') nutzen die einfache vertikale Kurve.
editor.createCurvature = (sx, sy, ex, ey, curvature, type) =>
(type && type !== 'openclose')
? verticalCurvature(sx, sy, ex, ey)
: routeConnection(state, sx, sy, ex, ey);
container.addEventListener('dragover', e => { container.addEventListener('dragover', e => {
e.preventDefault(); e.preventDefault();
@@ -95,17 +353,32 @@ function attach(host) {
const def = state.registry.get(typeId); const def = state.registry.get(typeId);
if (!def) return; if (!def) return;
const rect = container.getBoundingClientRect(); // Greif-Offset in Canvas-Einheiten abziehen (nicht in Bildschirm-
const zoom = editor.zoom; // Pixeln): So bleibt der Mauszeiger in jeder Zoomstufe an derselben
const px = (e.clientX - rect.left - editor.canvas_x) / zoom; // relativen Stelle im erzeugten Knoten, statt dass der Knoten beim
const py = (e.clientY - rect.top - editor.canvas_y) / zoom; // Herauszoomen um den hochgerechneten Offset neben der Maus landet.
const { x, y } = toCanvasPoint(state, e.clientX, e.clientY);
addNodeInternal(host, def, px, py); addNodeInternal(host, def, x - dragGrabOffset.x, y - dragGrabOffset.y);
}); });
editor.on('nodeSelected', id => { editor.on('nodeSelected', id => {
host.$server && host.$server.onNodeSelected(parseInt(id, 10)); host.$server && host.$server.onNodeSelected(parseInt(id, 10));
}); });
// Klick auf das Zahnrad-Icon eines Knotens -> Einstellungen öffnen.
container.addEventListener('mousedown', e => {
const gear = e.target instanceof Element ? e.target.closest('.task-node-gear') : null;
if (gear) e.stopPropagation(); // verhindert das Verschieben des Knotens
}, true);
container.addEventListener('click', e => {
const gear = e.target instanceof Element ? e.target.closest('.task-node-gear') : null;
if (!gear) return;
const nodeEl = gear.closest('.drawflow-node');
if (!nodeEl) return;
e.stopPropagation();
const id = parseInt(nodeEl.id.replace('node-', ''), 10);
host.$server && host.$server.onNodeActivated(id);
}, true);
editor.on('nodeUnselected', () => { editor.on('nodeUnselected', () => {
host.$server && host.$server.onNodeUnselected(); host.$server && host.$server.onNodeUnselected();
}); });
@@ -113,9 +386,264 @@ function attach(host) {
host.$server && host.$server.onNodeRemoved(parseInt(id, 10)); host.$server && host.$server.onNodeRemoved(parseInt(id, 10));
}); });
// Pro Ausgang ist nur eine Verbindung erlaubt. Hat ein Ausgang bereits eine
// Linie, wird Drawflows Verbindungs-Drag gar nicht erst gestartet: Das
// mousedown/touchstart auf dem Ausgangs-Punkt wird in der Capture-Phase
// abgefangen, bevor Drawflows eigener Handler ausgelöst wird.
const blockSecondConnectionStart = e => {
if (e.type === 'mousedown' && e.button !== 0) return;
const target = e.target;
if (!(target instanceof Element) || !target.classList.contains('output')) return;
const nodeEl = target.closest('.drawflow-node');
if (!nodeEl) return;
const id = parseInt(nodeEl.id.replace('node-', ''), 10);
const outputClass = Array.from(target.classList).find(c => c.startsWith('output_'));
if (!outputClass) return;
const node = editor.drawflow.drawflow[editor.module].data[id];
const output = node && node.outputs[outputClass];
if (output && output.connections.length >= 1) {
e.stopPropagation();
e.preventDefault();
}
};
container.addEventListener('mousedown', blockSecondConnectionStart, true);
container.addEventListener('touchstart', blockSecondConnectionStart, true);
// Sicherheitsnetz: Sollte auf anderem Weg dennoch eine zweite Verbindung am
// selben Ausgang entstehen, wird die neu erstellte sofort wieder entfernt.
editor.on('connectionCreated', conn => {
const data = editor.drawflow.drawflow[editor.module].data;
const node = data[conn.output_id];
const output = node && node.outputs[conn.output_class];
if (output && output.connections.length > 1) {
editor.removeSingleConnection(conn.output_id, conn.input_id, conn.output_class, conn.input_class);
}
});
// Unvollständig verdrahtete Elemente (offener Ein- oder Ausgang) hellrot
// markieren. Nach jeder strukturellen Änderung neu bewerten.
const refresh = () => requestAnimationFrame(() => refreshValidity(state));
editor.on('connectionCreated', refresh);
editor.on('connectionRemoved', refresh);
editor.on('nodeCreated', refresh);
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.
container.addEventListener('mousedown', e => {
if (e.button !== 0) return;
const cls = e.target instanceof Element ? e.target.classList : null;
const onBackground = cls && (cls.contains('parent-drawflow') || cls.contains('drawflow'));
if (!onBackground) return; // Klicks auf Knoten/Ports/Linien normal behandeln
const path = nearestConnectionPath(state, e.clientX, e.clientY, 12);
if (!path) return;
e.stopPropagation();
selectConnection(state, path);
}, true);
// 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 rightPan = null;
container.addEventListener('mousedown', e => {
if (e.button !== 2) return;
e.preventDefault();
e.stopPropagation(); // Drawflows eigene (Links-)Drag-Logik nicht auslösen
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 = () => {
// 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);
// 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 => {
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
// auslöst.
const onWheelZoom = e => {
e.preventDefault();
e.stopPropagation();
if (e.deltaY > 0) {
editor.zoom_out();
} else if (e.deltaY < 0) {
editor.zoom_in();
}
};
container.addEventListener('wheel', onWheelZoom, { capture: true, passive: false });
// Eine angeklickte Verbindung erhält den Fokus auf dem Canvas-Container,
// damit die Entf-/Backspace-Taste sie löschen kann.
editor.on('connectionSelected', () => {
container.focus({ preventScroll: true });
});
// Absicherung: Verbindung auch dann löschen, wenn der Canvas-Container nicht
// den Tastaturfokus hat (Drawflows eigener Handler hängt am Container).
const deleteSelectedConnection = e => {
if (e.key !== 'Delete' && e.key !== 'Backspace') return;
if (editor.connection_selected == null) return;
const active = document.activeElement;
const tag = active && active.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA'
|| (active && active.isContentEditable)) {
return; // Eingaben in Textfeldern nicht abfangen
}
e.preventDefault();
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 });
};
return state; return state;
} }
// Wandelt Client-Koordinaten in das (unskalierte) Canvas-Koordinatensystem um,
// 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 = editor.precanvas.getBoundingClientRect();
const zoom = editor.zoom || 1;
return {
x: (clientX - rect.left) / zoom,
y: (clientY - rect.top) / zoom,
zoom
};
}
// Sucht den Verbindungspfad, der einem Klickpunkt am nächsten liegt (innerhalb
// der Toleranz). Nur fertige Verbindungen (Drawflow-Klasse node_in_node-<id>).
function nearestConnectionPath(state, clientX, clientY, tolerancePx) {
const { x, y, zoom } = toCanvasPoint(state, clientX, clientY);
const tolerance = tolerancePx / zoom;
let best = null;
let bestDist = tolerance;
state.container
.querySelectorAll('.connection[class*="node_in_node-"] .main-path')
.forEach(path => {
let length;
try { length = path.getTotalLength(); } catch (e) { return; }
if (!length) return;
const step = Math.max(5, length / 80);
for (let d = 0; d <= length; d += step) {
const pt = path.getPointAtLength(d);
const dist = Math.hypot(pt.x - x, pt.y - y);
if (dist < bestDist) {
bestDist = dist;
best = path;
}
}
});
return best;
}
// Wählt eine Verbindung programmatisch aus (analog zu Drawflows interner
// main-path-Auswahl), damit sie hervorgehoben und per Entf löschbar ist.
function selectConnection(state, pathEl) {
const editor = state.editor;
if (editor.node_selected) {
editor.node_selected.classList.remove('selected');
editor.node_selected = null;
editor.dispatch('nodeUnselected', true);
}
if (editor.connection_selected) {
editor.connection_selected.classList.remove('selected');
}
editor.connection_selected = pathEl;
const parent = pathEl.parentElement;
parent.querySelectorAll('.main-path').forEach(p => p.classList.add('selected'));
const cl = parent.classList;
if (cl.length > 1) {
editor.dispatch('connectionSelected', {
output_id: cl[2].slice(14),
input_id: cl[1].slice(13),
output_class: cl[3],
input_class: cl[4]
});
}
state.container.focus({ preventScroll: true });
}
function addNodeInternal(host, def, x, y) { function addNodeInternal(host, def, x, y) {
const state = editors.get(host); const state = editors.get(host);
if (!state) return null; if (!state) return null;
@@ -150,6 +678,24 @@ window.taskListEditor = {
if (!def) return; if (!def) return;
addNodeInternal(host, def, x, y); addNodeInternal(host, def, x, y);
}, },
setNodeOutputs(host, nodeId, count) {
const state = editors.get(host);
if (!state) return;
const editor = state.editor;
const node = editor.getNodeFromId(nodeId);
if (!node) return;
let current = Object.keys(node.outputs || {}).length;
while (current < count) {
editor.addNodeOutput(nodeId);
current++;
}
while (current > count) {
editor.removeNodeOutput(nodeId, `output_${current}`);
current--;
}
recordHistory(state);
requestAnimationFrame(() => refreshValidity(state));
},
updateNodeLabel(host, nodeId, label) { updateNodeLabel(host, nodeId, label) {
const state = editors.get(host); const state = editors.get(host);
if (!state) return; if (!state) return;
@@ -157,12 +703,23 @@ window.taskListEditor = {
if (!node) return; if (!node) return;
const html = buildNodeHtml(label, state.registry.get(node.data.typeId)?.color || '#444'); const html = buildNodeHtml(label, state.registry.get(node.data.typeId)?.color || '#444');
state.editor.updateNodeDataFromId(nodeId, { ...node.data, label }); 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`); const el = state.container.querySelector(`#node-${nodeId} .drawflow_content_node`);
if (el) el.innerHTML = html; if (el) el.innerHTML = html;
recordHistory(state);
},
undo(host) {
const state = editors.get(host);
return state ? undoLast(state) : false;
}, },
clear(host) { clear(host) {
const state = editors.get(host); const state = editors.get(host);
if (state) state.editor.clear(); if (!state) return;
state.editor.clear();
recordHistory(state);
}, },
exportGraph(host) { exportGraph(host) {
const state = editors.get(host); const state = editors.get(host);
@@ -202,6 +759,8 @@ window.taskListEditor = {
state.editor.addConnection(ids[i], ids[i + 1], 'output_1', 'input_1'); 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); return JSON.stringify(ids);
}, },
importGraph(host, graphJson) { importGraph(host, graphJson) {
@@ -209,6 +768,8 @@ window.taskListEditor = {
if (!graphJson) return; if (!graphJson) return;
try { try {
state.editor.import(JSON.parse(graphJson)); state.editor.import(JSON.parse(graphJson));
// Frisch geladener Stand ist der neue Basiszustand der Undo-Historie.
resetHistory(state);
} catch (e) { } catch (e) {
console.error('importGraph failed', e); console.error('importGraph failed', e);
} }

View File

@@ -0,0 +1,448 @@
import Drawflow from 'drawflow';
import 'drawflow/dist/drawflow.min.css';
// Logik-Knotentypen des Script-Editors (Anzahl Ein-/Ausgänge).
const LOGIC = {
constant: { inputs: 0, outputs: 1 },
variable: { inputs: 0, outputs: 1 },
compare: { inputs: 2, outputs: 2 },
and: { inputs: 2, outputs: 1 },
or: { inputs: 2, outputs: 1 },
not: { inputs: 1, outputs: 1 },
if: { inputs: 1, outputs: 2 },
result: { inputs: 1, outputs: 0 },
output: { inputs: 1, outputs: 0 }
};
const scriptEditors = new WeakMap();
// Rastergröße passend zum gepunkteten Canvas-Hintergrund (24px).
const GRID = 24;
function snap(value) {
return Math.round(value / GRID) * GRID;
}
// Horizontale Kurvenführung: Linien treten waagerecht aus dem Ausgang aus
// und treten waagerecht in den Eingang ein (Ports liegen links/rechts).
function horizontalCurvature(sx, sy, ex, ey) {
const offset = Math.max(Math.abs(ex - sx) * 0.5, 40);
return ` M ${sx} ${sy} C ${sx + offset} ${sy} ${ex - offset} ${ey} ${ex} ${ey}`;
}
// --- Hindernis-bewusste Linienführung -------------------------------------
// createCurvature kennt nur die Endpunkte der Verbindung. Damit Linien nach
// Möglichkeit nicht über andere Kacheln laufen, lesen wir die Knoten-Rechtecke
// (in Canvas-Koordinaten) direkt aus dem DOM und leiten eine kreuzende Linie
// über einen freien horizontalen Kanal ober- oder unterhalb der Kacheln um.
const ROUTE_STUB = 26; // waagerechte Aus-/Eintrittsstrecke an den Ports
const ROUTE_PAD = 14; // Sicherheitsabstand um jede Kachel
const ROUTE_RADIUS = 12; // Eckenradius der Umleitung
// Knoten-Rechtecke als Hindernisse; Quell-/Zielknoten (die die Endpunkte
// enthalten) werden ausgeschlossen.
function obstacleRects(state, sx, sy, ex, ey) {
const rects = [];
state.container.querySelectorAll('.drawflow-node').forEach(el => {
const left = parseFloat(el.style.left) || 0;
const top = parseFloat(el.style.top) || 0;
const w = el.offsetWidth || 0;
const h = el.offsetHeight || 0;
if (!w || !h) return;
const r = {
left: left - ROUTE_PAD, top: top - ROUTE_PAD,
right: left + w + ROUTE_PAD, bottom: top + h + ROUTE_PAD
};
const hasStart = sx >= r.left && sx <= r.right && sy >= r.top && sy <= r.bottom;
const hasEnd = ex >= r.left && ex <= r.right && ey >= r.top && ey <= r.bottom;
if (hasStart || hasEnd) return;
rects.push(r);
});
return rects;
}
function pointInAnyRect(x, y, rects) {
return rects.some(r => x >= r.left && x <= r.right && y >= r.top && y <= r.bottom);
}
// Läuft die (abgetastete) Bézier-Kurve über eine Kachel?
function bezierHits(sx, sy, c1x, c1y, c2x, c2y, ex, ey, rects) {
const N = 24;
for (let i = 1; i < N; i++) {
const t = i / N, u = 1 - t;
const x = u * u * u * sx + 3 * u * u * t * c1x + 3 * u * t * t * c2x + t * t * t * ex;
const y = u * u * u * sy + 3 * u * u * t * c1y + 3 * u * t * t * c2y + t * t * t * ey;
if (pointInAnyRect(x, y, rects)) return true;
}
return false;
}
// Treffer-Test für eine achsenparallele Wegpunktkette (Segment-BBox == Segment).
function segmentsHit(points, rects) {
for (let i = 0; i < points.length - 1; i++) {
const a = points[i], b = points[i + 1];
const left = Math.min(a.x, b.x), right = Math.max(a.x, b.x);
const top = Math.min(a.y, b.y), bottom = Math.max(a.y, b.y);
if (rects.some(r => right >= r.left && left <= r.right && bottom >= r.top && top <= r.bottom)) {
return true;
}
}
return false;
}
// Wegpunkte: Aus dem Port heraus, über einen Kanal auf Höhe channelY und in
// den Zielport hinein.
function channelWaypoints(sx, sy, ex, ey, channelY) {
const ax = sx + ROUTE_STUB;
const bx = ex - ROUTE_STUB;
return [
{ x: sx, y: sy }, { x: ax, y: sy }, { x: ax, y: channelY },
{ x: bx, y: channelY }, { x: bx, y: ey }, { x: ex, y: ey }
];
}
// Glatter Pfad mit abgerundeten Ecken durch achsenparallele Wegpunkte.
function roundedPath(pts, radius) {
const points = [];
for (const p of pts) {
const last = points[points.length - 1];
if (!last || Math.abs(last.x - p.x) > 0.5 || Math.abs(last.y - p.y) > 0.5) points.push(p);
}
if (points.length < 2) return '';
if (points.length === 2) {
return `M ${points[0].x} ${points[0].y} L ${points[1].x} ${points[1].y}`;
}
let d = `M ${points[0].x} ${points[0].y}`;
for (let i = 1; i < points.length - 1; i++) {
const p0 = points[i - 1], p1 = points[i], p2 = points[i + 1];
const v1x = p1.x - p0.x, v1y = p1.y - p0.y;
const v2x = p2.x - p1.x, v2y = p2.y - p1.y;
const len1 = Math.hypot(v1x, v1y) || 1;
const len2 = Math.hypot(v2x, v2y) || 1;
const rr = Math.min(radius, len1 / 2, len2 / 2);
const s1x = p1.x - (v1x / len1) * rr, s1y = p1.y - (v1y / len1) * rr;
const e1x = p1.x + (v2x / len2) * rr, e1y = p1.y + (v2y / len2) * rr;
d += ` L ${s1x} ${s1y} Q ${p1.x} ${p1.y} ${e1x} ${e1y}`;
}
const last = points[points.length - 1];
d += ` L ${last.x} ${last.y}`;
return d;
}
// Liefert den SVG-Pfad einer Verbindung direkt, falls frei, sonst umgeleitet.
function routeConnection(state, sx, sy, ex, ey) {
const offset = Math.max(Math.abs(ex - sx) * 0.5, 40);
const c1x = sx + offset, c2x = ex - offset;
const direct = ` M ${sx} ${sy} C ${c1x} ${sy} ${c2x} ${ey} ${ex} ${ey}`;
const rects = obstacleRects(state, sx, sy, ex, ey);
if (rects.length === 0 || !bezierHits(sx, sy, c1x, sy, c2x, ey, ex, ey, rects)) {
return direct;
}
// Kacheln, die im waagerechten Bereich zwischen Quelle und Ziel liegen.
const spanLeft = Math.min(sx, ex), spanRight = Math.max(sx, ex);
const blockers = rects.filter(r => r.right > spanLeft && r.left < spanRight);
if (blockers.length === 0) return direct;
const ref = (sy + ey) / 2;
const aboveY = Math.min(...blockers.map(r => r.top)) - ROUTE_PAD;
const belowY = Math.max(...blockers.map(r => r.bottom)) + ROUTE_PAD;
const first = Math.abs(aboveY - ref) <= Math.abs(belowY - ref) ? aboveY : belowY;
const second = first === aboveY ? belowY : aboveY;
let wp = channelWaypoints(sx, sy, ex, ey, first);
if (segmentsHit(wp, rects)) {
const alt = channelWaypoints(sx, sy, ex, ey, second);
if (!segmentsHit(alt, rects)) wp = alt;
}
return roundedPath(wp, ROUTE_RADIUS);
}
// Drag-Start für die Operator-Kacheln (einmalig global registrieren).
if (!window.__scriptEditorDragInit) {
window.__scriptEditorDragInit = true;
document.addEventListener('dragstart', e => {
const target = e.target instanceof Element ? e.target.closest('[data-logictype]') : null;
if (target && e.dataTransfer) {
e.dataTransfer.setData('application/x-logictype', target.dataset.logictype);
e.dataTransfer.effectAllowed = 'copy';
}
}, true);
}
function logicHtml(typeId) {
switch (typeId) {
case 'constant':
return `<div class="logic-node logic-constant">
<div class="logic-node-title">Konstante</div>
<input df-const class="logic-input" placeholder="Wert">
</div>`;
case 'variable':
return `<div class="logic-node logic-variable">
<div class="logic-node-title">Variable</div>
<select df-source class="logic-select"></select>
</div>`;
case 'compare':
return `<div class="logic-node logic-compare">
<div class="logic-node-title">Vergleich</div>
<select df-operator class="logic-select">
<option value="==">=</option>
<option value="!=">&ne;</option>
<option value="&lt;">&lt;</option>
<option value="&gt;">&gt;</option>
<option value="&lt;=">&le;</option>
<option value="&gt;=">&ge;</option>
</select>
<div class="logic-ports">Eing&auml;nge: oben links &middot; unten rechts</div>
<div class="logic-ports">Ausg&auml;nge: oben &bdquo;trifft zu&ldquo; &middot; unten &bdquo;trifft nicht zu&ldquo;</div>
</div>`;
case 'and':
return `<div class="logic-node logic-bool"><div class="logic-node-title">UND</div></div>`;
case 'or':
return `<div class="logic-node logic-bool"><div class="logic-node-title">ODER</div></div>`;
case 'not':
return `<div class="logic-node logic-bool"><div class="logic-node-title">NICHT</div></div>`;
case 'if':
return `<div class="logic-node logic-if">
<div class="logic-node-title">Wenn</div>
<div class="logic-ports">&#9312; Dann &middot; &#9313; Sonst</div>
</div>`;
case 'result':
return `<div class="logic-node logic-result">
<div class="logic-node-title">Ergebnis</div>
<input df-result class="logic-input" placeholder="Ergebniswert">
</div>`;
case 'output':
return `<div class="logic-node logic-output">
<div class="logic-node-title">Ausgang</div>
<input df-name class="logic-input" placeholder="Bezeichnung">
</div>`;
default:
return `<div class="logic-node"><div class="logic-node-title">?</div></div>`;
}
}
function defaultData(typeId) {
switch (typeId) {
case 'constant': return { type: typeId, const: '' };
case 'variable': return { type: typeId, source: '' };
case 'compare': return { type: typeId, operator: '==' };
case 'result': return { type: typeId, result: '' };
case 'output': return { type: typeId, name: '' };
default: return { type: typeId };
}
}
// Füllt das Variablen-Dropdown eines Wert-Knotens mit den verfügbaren
// Variablen (= eingegebene Daten der anderen Elemente) und erhält die
// gespeicherte Auswahl.
function fillSourceSelect(select, variables, current) {
const cur = current == null ? '' : String(current);
select.innerHTML = '';
const empty = document.createElement('option');
empty.value = '';
empty.textContent = ' Variable wählen ';
select.appendChild(empty);
let found = false;
for (const v of variables) {
const option = document.createElement('option');
option.value = String(v.key);
option.textContent = v.label;
if (String(v.key) === cur) {
option.selected = true;
found = true;
}
select.appendChild(option);
}
if (cur && !found) {
const option = document.createElement('option');
option.value = cur;
option.textContent = '(entferntes Element)';
option.selected = true;
select.appendChild(option);
}
}
// Zeichnet alle Verbindungslinien des Graphen neu. Notwendig nach einem
// Import, da Drawflow die Linien aus den Bildschirmkoordinaten der Ports
// berechnet.
function redrawConnections(state) {
const modules = state.editor.drawflow.drawflow;
for (const moduleName in modules) {
for (const id in modules[moduleName].data) {
state.editor.updateConnectionNodes(`node-${id}`);
}
}
}
// Wird der Graph importiert, während der Dialog-Container noch nicht sichtbar
// bzw. noch in der Öffnungs-Animation ist, berechnet Drawflow die Verbindungen
// aus falschen (skalierten oder nicht vorhandenen) Port-Koordinaten und schreibt
// diese fest in die SVG-Pfade die Linien sitzen dann neben den Ports oder
// kollabieren auf den Nullpunkt.
//
// Daher die Linien zunächst jeden Frame neu zeichnen, bis sich die
// Container-Geometrie (Größe und Position) über mehrere Frames nicht mehr
// ändert (= Dialog-Animation abgeschlossen). Zusätzlich noch einige gestaffelte
// Neuberechnungen, um späte Reflows (Font-Laden, verzögertes Layout) abzufangen.
function redrawConnectionsWhenReady(state) {
let lastKey = null;
let stableFrames = 0;
let frames = 0;
const tick = () => {
const c = state.container;
if (c.clientWidth > 0 && c.clientHeight > 0) {
const r = c.getBoundingClientRect();
const key = [r.left, r.top, r.width, r.height].map(Math.round).join('x');
redrawConnections(state);
if (key === lastKey) {
if (++stableFrames >= 3) return;
} else {
stableFrames = 0;
lastKey = key;
}
}
if (frames++ < 120) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
// Insurance gegen späte Layout-Änderungen nach abgeschlossener Animation.
for (const delay of [150, 350, 600]) {
setTimeout(() => {
if (state.container.clientWidth > 0 && state.container.clientHeight > 0) {
redrawConnections(state);
}
}, delay);
}
}
function refreshVariableSelects(state) {
const modules = state.editor.drawflow.drawflow;
for (const moduleName in modules) {
const data = modules[moduleName].data;
for (const id in data) {
const node = data[id];
if (node.name !== 'variable') continue;
const select = state.container.querySelector(`#node-${id} select[df-source]`);
if (!select) continue;
const current = node.data && node.data.source != null ? node.data.source : '';
fillSourceSelect(select, state.variables, current);
}
}
}
function attach(host) {
if (scriptEditors.has(host)) {
return scriptEditors.get(host);
}
host.classList.add('script-editor');
host.innerHTML = '';
const container = document.createElement('div');
container.className = 'script-editor-container';
container.style.width = '100%';
container.style.height = '100%';
host.appendChild(container);
const editor = new Drawflow(container);
editor.reroute = true;
editor.start();
const state = { editor, container, counter: 0, variables: [] };
scriptEditors.set(host, state);
// Hindernis-bewusste, horizontale Linienführung (statt der vertikalen aus
// dem Workflow-Editor). Für Verbindungssegmente mit Reroute-Punkten
// (type != 'openclose') greift die einfache Kurve.
editor.createCurvature = (sx, sy, ex, ey, curvature, type) =>
(type && type !== 'openclose')
? horizontalCurvature(sx, sy, ex, ey)
: routeConnection(state, sx, sy, ex, ey);
container.addEventListener('dragover', e => {
e.preventDefault();
if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy';
});
container.addEventListener('drop', e => {
e.preventDefault();
const typeId = e.dataTransfer ? e.dataTransfer.getData('application/x-logictype') : '';
if (!typeId || !LOGIC[typeId]) return;
const rect = container.getBoundingClientRect();
const zoom = editor.zoom;
const x = (e.clientX - rect.left - editor.canvas_x) / zoom;
const y = (e.clientY - rect.top - editor.canvas_y) / zoom;
addNodeAt(state, typeId, x, y);
});
// Knoten nach dem Verschieben am Raster einrasten.
editor.on('nodeMoved', id => {
const el = container.querySelector(`#node-${id}`);
if (!el) return;
const x = snap(parseFloat(el.style.left) || 0);
const y = snap(parseFloat(el.style.top) || 0);
el.style.left = `${x}px`;
el.style.top = `${y}px`;
const node = editor.drawflow.drawflow[editor.module].data[id];
if (node) {
node.pos_x = x;
node.pos_y = y;
}
editor.updateConnectionNodes(`node-${id}`);
});
return state;
}
function addNodeAt(state, typeId, x, y) {
const def = LOGIC[typeId];
if (!def) return;
state.editor.addNode(typeId, def.inputs, def.outputs, snap(x), snap(y), `logic-${typeId}`, defaultData(typeId), logicHtml(typeId));
if (typeId === 'variable') {
refreshVariableSelects(state);
}
}
function addNode(host, typeId) {
const state = attach(host);
const n = state.counter++;
addNodeAt(state, typeId, 60 + (n % 6) * 50, 50 + (n % 6) * 45);
}
window.scriptEditor = {
attach,
addNode,
setVariables(host, variables) {
const state = attach(host);
state.variables = Array.isArray(variables) ? variables : [];
refreshVariableSelects(state);
// Geänderte Dropdown-Inhalte können die Knotenbreite und damit die
// Portpositionen verschieben Verbindungen neu zeichnen.
redrawConnectionsWhenReady(state);
},
clear(host) {
const state = scriptEditors.get(host);
if (state) state.editor.clear();
},
setGraph(host, json) {
const state = attach(host);
if (!json) {
state.editor.clear();
return;
}
try {
state.editor.import(JSON.parse(json));
refreshVariableSelects(state);
redrawConnectionsWhenReady(state);
} catch (e) {
console.error('scriptEditor.setGraph failed', e);
state.editor.clear();
}
},
exportGraph(host) {
const state = scriptEditors.get(host);
if (!state) return '';
return JSON.stringify(state.editor.export());
}
};

View File

@@ -116,6 +116,9 @@ body, .tasklist-app {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 2px; gap: 2px;
/* Erlaubt dem Textblock, im Flex-Layout zu schrumpfen, statt zu überlaufen. */
min-width: 0;
flex: 1;
} }
.palette-item-label { .palette-item-label {
@@ -127,6 +130,67 @@ body, .tasklist-app {
.palette-item-desc { .palette-item-desc {
color: var(--tle-muted); color: var(--tle-muted);
font-size: var(--lumo-font-size-xs); font-size: var(--lumo-font-size-xs);
/* Lange Wörter umbrechen, damit der Text nicht in den Papierkorb läuft. */
overflow-wrap: anywhere;
}
/* Trenner zwischen festen und benutzerdefinierten Elementen. */
.palette-divider {
display: flex;
align-items: center;
gap: var(--lumo-space-s);
margin: var(--lumo-space-m) 0 var(--lumo-space-s);
color: var(--tle-muted);
font-size: var(--lumo-font-size-xs);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.palette-divider::before,
.palette-divider::after {
content: "";
flex: 1;
height: 1px;
background: var(--tle-border);
}
.palette-divider-label {
white-space: nowrap;
font-weight: 600;
}
/* Markierung der benutzerdefinierten Elemente. */
.palette-item-custom {
position: relative;
/* Rechts einen vertikalen Streifen für den Papierkorb reservieren,
damit der Text nicht hineinläuft und unten keine Extra-Zeile entsteht. */
padding-right: calc(var(--lumo-space-m) + 26px);
border-style: dashed;
background:
linear-gradient(0deg, rgba(37, 99, 235, 0.14), rgba(37, 99, 235, 0.14)),
var(--tle-panel);
}
.palette-item-delete {
position: absolute;
right: var(--lumo-space-s);
bottom: var(--lumo-space-s);
width: 18px;
height: 18px;
padding: 2px;
color: var(--tle-muted);
cursor: pointer;
opacity: 0.5;
transition: color 120ms ease, opacity 120ms ease, transform 120ms ease;
}
.palette-item-custom:hover .palette-item-delete {
opacity: 1;
}
.palette-item-delete:hover {
color: var(--lumo-error-color, #e53935);
transform: scale(1.15);
} }
.node-editor-host { .node-editor-host {
@@ -168,7 +232,11 @@ body, .tasklist-app {
pointer-events: none; pointer-events: none;
} }
.task-list-editor .drawflow .connection[class*="node_in_node_"] .main-path { /* Nur fertige Verbindungen sind anklickbar; die in Entstehung befindliche
Verbindung (ohne node_in_node--Klasse) bleibt unberührt, damit das
Verbinden per Drag nicht gestört wird.
Hinweis: Drawflow vergibt die Klasse mit Bindestrich (node_in_node-<id>). */
.task-list-editor .drawflow .connection[class*="node_in_node-"] .main-path {
pointer-events: stroke; pointer-events: stroke;
} }
@@ -181,6 +249,7 @@ body, .tasklist-app {
} }
.task-node { .task-node {
position: relative;
background: var(--tle-panel); background: var(--tle-panel);
border: 1px solid var(--tle-border); border: 1px solid var(--tle-border);
border-radius: 10px; border-radius: 10px;
@@ -192,6 +261,43 @@ body, .tasklist-app {
flex-direction: column; flex-direction: column;
} }
/* Unvollständig verdrahtetes Element (offener Ein- oder Ausgang): hellrot. */
.drawflow-node.node-incomplete .task-node {
background: #ffdede;
border-color: #ef4444;
}
.task-node-gear {
position: absolute;
top: 12px;
right: 12px;
width: 18px;
height: 18px;
color: var(--tle-muted, #6b7280);
opacity: 0.55;
cursor: pointer;
z-index: 6;
transition: opacity 0.15s ease, color 0.15s ease;
}
.task-node-gear:hover {
opacity: 1;
color: var(--tle-text, #1f2933);
}
.task-node-gear svg {
width: 100%;
height: 100%;
display: block;
pointer-events: none;
}
/* Virtuelle Workflow-Markierungen (Start/Abschluss) haben keine Einstellungen. */
.type-start .task-node-gear,
.type-abschluss .task-node-gear {
display: none;
}
.task-node-header { .task-node-header {
height: 6px; height: 6px;
width: 100%; width: 100%;
@@ -265,12 +371,19 @@ body, .tasklist-app {
.task-list-editor .drawflow .connection .main-path { .task-list-editor .drawflow .connection .main-path {
stroke: #94a3b8; stroke: #94a3b8;
stroke-width: 2.5px; stroke-width: 4px;
} }
.task-list-editor .drawflow .connection .main-path:hover { .task-list-editor .drawflow .connection .main-path:hover {
stroke: var(--tle-accent); stroke: var(--tle-accent);
stroke-width: 3px; stroke-width: 5px;
cursor: pointer;
}
/* Ausgewählte Verbindung hervorgehoben und als löschbar markiert. */
.task-list-editor .drawflow .connection .main-path.selected {
stroke: var(--lumo-error-color, #e53935);
stroke-width: 5px;
} }
.properties-content { .properties-content {
@@ -316,3 +429,178 @@ body, .tasklist-app {
font-size: var(--lumo-font-size-s); font-size: var(--lumo-font-size-s);
margin: 0 0 var(--lumo-space-s); margin: 0 0 var(--lumo-space-s);
} }
.properties-fieldlist-label {
color: var(--lumo-secondary-text-color);
font-size: var(--lumo-font-size-s);
font-weight: 500;
margin-bottom: var(--lumo-space-xs);
}
/* --- Script-/Logik-Editor --- */
.script-editor,
.script-editor-container {
height: 100%;
width: 100%;
}
/* Raster-Hintergrund wie im Workflow-Editor. */
.script-editor-host {
background:
radial-gradient(circle, var(--tle-canvas-grid) 1px, transparent 1px) 0 0 / 24px 24px,
var(--tle-canvas-bg);
overflow: hidden;
position: relative;
}
.script-editor .drawflow {
background: transparent;
}
.script-editor .drawflow .drawflow-node {
background: transparent;
border: none;
padding: 0;
box-shadow: none;
min-width: 150px;
}
/* Keine roten Ecken bei selektierten Knoten (Drawflow-Default überschreiben). */
.script-editor .drawflow .drawflow-node.selected {
background: transparent;
}
.logic-node {
background: var(--tle-panel, #fff);
border: 1px solid var(--tle-border, #d8dee9);
border-radius: 8px;
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.08);
padding: 8px 10px;
min-width: 150px;
display: flex;
flex-direction: column;
gap: 6px;
}
.logic-node-title {
font-weight: 600;
font-size: var(--lumo-font-size-s);
color: var(--tle-text, #1f2933);
text-align: center;
}
.logic-node .logic-input,
.logic-node .logic-select {
width: 100%;
box-sizing: border-box;
font-size: var(--lumo-font-size-xs);
padding: 4px 6px;
border: 1px solid var(--tle-border, #d8dee9);
border-radius: 6px;
}
.logic-ports {
font-size: 10px;
color: var(--tle-muted, #6b7280);
text-align: center;
}
.logic-node.logic-compare { border-top: 3px solid #2563eb; }
.logic-node.logic-if { border-top: 3px solid #d97706; }
.logic-node.logic-bool { border-top: 3px solid #7c3aed; }
.logic-node.logic-constant { border-top: 3px solid #0891b2; }
.logic-node.logic-variable { border-top: 3px solid #059669; }
.logic-node.logic-result { border-top: 3px solid #dc2626; }
.logic-node.logic-output { border-top: 3px solid #0f766e; }
/* Verfügbare Variablen im Script-Dialog */
.script-vars {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
padding: 8px 10px;
background: var(--lumo-contrast-5pct);
border-radius: var(--lumo-border-radius-m);
}
.script-vars-label {
font-weight: 600;
font-size: var(--lumo-font-size-s);
color: var(--tle-text, #1f2933);
}
.script-vars-empty {
font-size: var(--lumo-font-size-s);
color: var(--tle-muted, #6b7280);
font-style: italic;
}
.script-var-chip {
font-size: var(--lumo-font-size-xs);
padding: 2px 10px;
border-radius: 999px;
background: #059669;
color: #fff;
}
/* Operatoren-Palette links im Script-Dialog */
.script-palette {
flex-shrink: 0;
overflow-y: auto;
padding: 8px;
gap: 6px;
background: var(--lumo-contrast-5pct);
border-radius: var(--lumo-border-radius-m);
}
.script-palette .panel-heading {
margin: 0 0 4px;
font-size: var(--lumo-font-size-s);
color: var(--tle-muted, #6b7280);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.script-tile {
display: flex;
align-items: center;
gap: var(--lumo-space-s);
padding: 6px 8px;
border: 1px solid var(--tle-border);
border-radius: 9px;
background: var(--tle-panel);
cursor: grab;
user-select: none;
transition: border-color 120ms ease, transform 120ms ease, box-shadow 120ms ease;
}
.script-tile:hover {
border-color: var(--block-color, var(--tle-border));
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(15, 23, 42, 0.1);
}
.script-tile:active {
cursor: grabbing;
}
.script-tile-icon {
width: 26px;
height: 26px;
border-radius: 7px;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
font-weight: 700;
font-size: 14px;
line-height: 1;
flex-shrink: 0;
}
.script-tile-label {
font-weight: 600;
color: var(--tle-text);
font-size: var(--lumo-font-size-s);
}

View File

@@ -53,10 +53,25 @@ public class NodeEditor extends Div {
getElement().executeJs("window.taskListEditor.updateNodeLabel(this, $0, $1)", nodeId, label); getElement().executeJs("window.taskListEditor.updateNodeLabel(this, $0, $1)", nodeId, label);
} }
/** Setzt die Anzahl der Ausgänge eines Knotens (z. B. für Script-Elemente). */
public void setNodeOutputs(int nodeId, int count) {
getElement().executeJs("window.taskListEditor.setNodeOutputs(this, $0, $1)", nodeId, count);
}
public void clear() { public void clear() {
getElement().executeJs("window.taskListEditor.clear(this)"); 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 * Liest den aktuellen Drawflow-Graphen (Knoten + Verbindungen) als
* JSON-String aus dem Client und übergibt ihn an den Callback. * JSON-String aus dem Client und übergibt ihn an den Callback.
@@ -98,6 +113,10 @@ public class NodeEditor extends Div {
return addListener(NodeSelectedEvent.class, listener); return addListener(NodeSelectedEvent.class, listener);
} }
public Registration addNodeActivatedListener(ComponentEventListener<NodeActivatedEvent> listener) {
return addListener(NodeActivatedEvent.class, listener);
}
public Registration addNodeUnselectedListener(ComponentEventListener<NodeUnselectedEvent> listener) { public Registration addNodeUnselectedListener(ComponentEventListener<NodeUnselectedEvent> listener) {
return addListener(NodeUnselectedEvent.class, listener); return addListener(NodeUnselectedEvent.class, listener);
} }
@@ -106,6 +125,10 @@ public class NodeEditor extends Div {
return addListener(NodeRemovedEvent.class, listener); return addListener(NodeRemovedEvent.class, listener);
} }
public Registration addCanvasRestoredListener(ComponentEventListener<CanvasRestoredEvent> listener) {
return addListener(CanvasRestoredEvent.class, listener);
}
@ClientCallable @ClientCallable
private void onNodeAdded(int nodeId, String typeId) { private void onNodeAdded(int nodeId, String typeId) {
fireEvent(new NodeAddedEvent(this, nodeId, typeId)); fireEvent(new NodeAddedEvent(this, nodeId, typeId));
@@ -116,6 +139,11 @@ public class NodeEditor extends Div {
fireEvent(new NodeSelectedEvent(this, nodeId)); fireEvent(new NodeSelectedEvent(this, nodeId));
} }
@ClientCallable
private void onNodeActivated(int nodeId) {
fireEvent(new NodeActivatedEvent(this, nodeId));
}
@ClientCallable @ClientCallable
private void onNodeUnselected() { private void onNodeUnselected() {
fireEvent(new NodeUnselectedEvent(this)); fireEvent(new NodeUnselectedEvent(this));
@@ -126,6 +154,11 @@ public class NodeEditor extends Div {
fireEvent(new NodeRemovedEvent(this, nodeId)); fireEvent(new NodeRemovedEvent(this, nodeId));
} }
@ClientCallable
private void onCanvasRestored(String nodesJson) {
fireEvent(new CanvasRestoredEvent(this, nodesJson));
}
public static class NodeAddedEvent extends ComponentEvent<NodeEditor> { public static class NodeAddedEvent extends ComponentEvent<NodeEditor> {
private final int nodeId; private final int nodeId;
private final String typeId; private final String typeId;
@@ -151,6 +184,17 @@ public class NodeEditor extends Div {
public int nodeId() { return nodeId; } public int nodeId() { return nodeId; }
} }
public static class NodeActivatedEvent extends ComponentEvent<NodeEditor> {
private final int nodeId;
public NodeActivatedEvent(NodeEditor source, int nodeId) {
super(source, true);
this.nodeId = nodeId;
}
public int nodeId() { return nodeId; }
}
public static class NodeUnselectedEvent extends ComponentEvent<NodeEditor> { public static class NodeUnselectedEvent extends ComponentEvent<NodeEditor> {
public NodeUnselectedEvent(NodeEditor source) { public NodeUnselectedEvent(NodeEditor source) {
super(source, true); super(source, true);
@@ -167,4 +211,20 @@ public class NodeEditor extends Div {
public int nodeId() { return nodeId; } 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; }
}
} }

View File

@@ -0,0 +1,61 @@
package de.assecutor.tasklisteditor.component;
import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.function.SerializableConsumer;
import elemental.json.JsonArray;
/**
* Eigenständiger Logik-Canvas (Drawflow) zum grafischen Zusammenstecken
* kleiner Code-Snippets innerhalb eines Script-Blocks.
*
* <p>Die Eigenschaften der Logik-Knoten (Operator, Wert, Ergebnis …) werden
* über Drawflow-{@code df-}-Bindings direkt im Knoten gepflegt und sind daher
* Teil des exportierten Graph-JSON.
*/
@JsModule("./node-editor/script-editor.js")
@NpmPackage(value = "drawflow", version = "0.0.59")
public class ScriptEditor extends Div {
public ScriptEditor() {
addClassName("script-editor-host");
getElement().getStyle().set("width", "100%").set("height", "100%");
}
@Override
protected void onAttach(AttachEvent attachEvent) {
super.onAttach(attachEvent);
getElement().executeJs("window.scriptEditor.attach(this)");
}
/** Fügt einen Logik-Knoten des angegebenen Typs hinzu. */
public void addNode(String typeId) {
getElement().executeJs("window.scriptEditor.addNode(this, $0)", typeId);
}
/** Lädt einen zuvor exportierten Logik-Graphen (JSON) in den Canvas. */
public void setGraph(String json) {
getElement().executeJs("window.scriptEditor.setGraph(this, $0)", json);
}
/**
* Stellt die verfügbaren Variablen (eingegebene Daten der anderen
* Elemente) für die Wert-Knoten bereit. Erwartet ein JSON-Array aus
* Objekten mit {@code key} und {@code label}.
*/
public void setVariables(JsonArray variables) {
getElement().executeJs("window.scriptEditor.setVariables(this, $0)", variables);
}
public void clear() {
getElement().executeJs("window.scriptEditor.clear(this)");
}
/** Liest den aktuellen Logik-Graphen als JSON-String aus. */
public void exportGraph(SerializableConsumer<String> callback) {
getElement().executeJs("return window.scriptEditor.exportGraph(this)")
.then(String.class, callback::accept);
}
}

View File

@@ -0,0 +1,50 @@
package de.assecutor.tasklisteditor.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
/**
* Konfiguration der MongoDB-Collections, in denen die Einstellungen der
* einzelnen Element-Typen abgelegt werden.
*
* <p>Die Collection-Namen werden aus {@code application.properties} gebunden,
* deren Werte wiederum aus den {@code MONGODB_ELEMENT_*}-Variablen der
* {@code .env} stammen:
* <pre>
* tasklist.element-collections[text-liste-erfassen]=${MONGODB_ELEMENT_TEXT_LISTE_COLLECTION:element_text_liste_erfassen}
* </pre>
*
* <p>Für jeden (festen wie benutzerdefinierten) Typ muss eine Zuordnung
* existieren; benutzerdefinierte Typen werden zuvor auf ihren statischen
* Basistyp aufgelöst. Fehlt ein Eintrag, ist das ein Konfigurationsfehler.
*/
@Component
@ConfigurationProperties(prefix = "tasklist")
public class ElementCollectionProperties {
/** Typ-ID → Collection-Name. */
private final Map<String, String> elementCollections = new HashMap<>();
public Map<String, String> getElementCollections() {
return elementCollections;
}
/**
* Liefert den Collection-Namen für die angegebene Typ-ID.
*
* @throws IllegalStateException wenn für die Typ-ID keine Zuordnung
* konfiguriert ist
*/
public String collectionFor(String typeId) {
String configured = elementCollections.get(typeId);
if (configured == null || configured.isBlank()) {
throw new IllegalStateException(
"Keine Collection für Element-Typ '" + typeId + "' konfiguriert "
+ "(tasklist.element-collections).");
}
return configured;
}
}

View File

@@ -0,0 +1,135 @@
package de.assecutor.tasklisteditor.document;
import de.assecutor.tasklisteditor.model.CustomPropertyState;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.Instant;
import java.util.List;
/**
* In MongoDB gespeicherter benutzerdefinierter Typ. Enthält alle Daten, um den
* {@code BlockType} ohne Rückgriff auf den Basis-Typ wiederherstellen zu können
* (Aussehen, Ein-/Ausgänge und die Eigenschaften mit ihren erfassten Vorgaben).
*/
@Document(collection = "${MONGODB_CUSTOM_TYPE_COLLECTION:custom_types}")
public class CustomTypeDocument {
@Id
private String id;
/** Eindeutige Typnummer (>= 1000); dient zugleich als Schlüssel. */
@Indexed(unique = true)
private int taskType;
private String typeId;
private String label;
private String baseTypeId;
private String description;
private String icon;
private String color;
private int inputs;
private int outputs;
private List<CustomPropertyState> properties;
private Instant createdAt;
public CustomTypeDocument() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getTaskType() {
return taskType;
}
public void setTaskType(int taskType) {
this.taskType = taskType;
}
public String getTypeId() {
return typeId;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getBaseTypeId() {
return baseTypeId;
}
public void setBaseTypeId(String baseTypeId) {
this.baseTypeId = baseTypeId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getInputs() {
return inputs;
}
public void setInputs(int inputs) {
this.inputs = inputs;
}
public int getOutputs() {
return outputs;
}
public void setOutputs(int outputs) {
this.outputs = outputs;
}
public List<CustomPropertyState> getProperties() {
return properties;
}
public void setProperties(List<CustomPropertyState> properties) {
this.properties = properties;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
}

View File

@@ -0,0 +1,136 @@
package de.assecutor.tasklisteditor.document;
import org.springframework.data.annotation.Id;
import java.time.Instant;
import java.util.Map;
/**
* Einstellungen eines einzelnen platzierten Elements (Block-Instanz) eines
* Canvas. Wird beim Speichern eines Canvas je Element-Typ in eine eigene
* MongoDB-Collection geschrieben (Collection-Name pro Typ konfigurierbar, siehe
* {@code tasklist.element-collections} bzw. die {@code MONGODB_ELEMENT_*}-
* Variablen in der {@code .env}).
*
* <p>Die Verknüpfung zum Canvas erfolgt über {@link #canvasId}; {@link #nodeId}
* identifiziert den Knoten innerhalb des Canvas.
*/
public class ElementSettingsDocument {
@Id
private String id;
/** ID des zugehörigen {@link CanvasDocument}. */
private String canvasId;
/** Anzeigename des Canvas zum Zeitpunkt des Speicherns. */
private String canvasName;
/** Knoten-ID innerhalb des Canvas (Drawflow). */
private int nodeId;
/** Typ-ID des Elements (z. B. {@code text-liste-erfassen} oder {@code custom-1000}). */
private String typeId;
/**
* Bei benutzerdefinierten Typen die Typ-ID des statischen Basistyps, in
* dessen Collection das Dokument abgelegt wird; bei festen Typen {@code null}.
*/
private String baseTypeId;
/** Bezeichnung des Tasks (entspricht {@code topic}). */
private String topic;
/** Erfasste Property-Werte des Elements. */
private Map<String, Object> values;
private Instant createdAt;
public ElementSettingsDocument() {
}
public ElementSettingsDocument(String canvasId, String canvasName, int nodeId,
String typeId, String baseTypeId, String topic,
Map<String, Object> values, Instant createdAt) {
this.canvasId = canvasId;
this.canvasName = canvasName;
this.nodeId = nodeId;
this.typeId = typeId;
this.baseTypeId = baseTypeId;
this.topic = topic;
this.values = values;
this.createdAt = createdAt;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCanvasId() {
return canvasId;
}
public void setCanvasId(String canvasId) {
this.canvasId = canvasId;
}
public String getCanvasName() {
return canvasName;
}
public void setCanvasName(String canvasName) {
this.canvasName = canvasName;
}
public int getNodeId() {
return nodeId;
}
public void setNodeId(int nodeId) {
this.nodeId = nodeId;
}
public String getTypeId() {
return typeId;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public String getBaseTypeId() {
return baseTypeId;
}
public void setBaseTypeId(String baseTypeId) {
this.baseTypeId = baseTypeId;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public Map<String, Object> getValues() {
return values;
}
public void setValues(Map<String, Object> values) {
this.values = values;
}
public Instant getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Instant createdAt) {
this.createdAt = createdAt;
}
}

View File

@@ -11,6 +11,22 @@ public record BlockType(
int taskType, int taskType,
int inputs, int inputs,
int outputs, int outputs,
List<PropertyDefinition> properties List<PropertyDefinition> properties,
/** Verweis auf den statischen Basistyp (nur bei benutzerdefinierten Typen, sonst {@code null}). */
String baseTypeId
) { ) {
/** Konstruktor für feste Standard-Typen ohne Basistyp-Verweis. */
public BlockType(String id, String label, String description, String icon, String color,
int taskType, int inputs, int outputs, List<PropertyDefinition> properties) {
this(id, label, description, icon, color, taskType, inputs, outputs, properties, null);
}
/**
* Rein virtuelle Blöcke (z.&nbsp;B. Start/Abschluss) dienen nur der
* Workflow-Darstellung im Canvas und werden nicht in die Task-Liste
* exportiert. Sie sind an einer negativen Typnummer erkennbar.
*/
public boolean isVirtual() {
return taskType < 0;
}
} }

View File

@@ -1,5 +1,6 @@
package de.assecutor.tasklisteditor.model; package de.assecutor.tasklisteditor.model;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@@ -21,14 +22,46 @@ public class BlockTypeRegistry {
private final Map<String, BlockType> types = new LinkedHashMap<>(); private final Map<String, BlockType> types = new LinkedHashMap<>();
public BlockTypeRegistry() { /** Typnummer der virtuellen Start-Markierung (negativ = nicht exportiert). */
public static final int START_TASK_TYPE = -1;
/** Typnummer der virtuellen Abschluss-Markierung (negativ = nicht exportiert). */
public static final int END_TASK_TYPE = -2;
public BlockTypeRegistry(@Value("${tasklist.hide-script-block:false}") boolean hideScriptBlock) {
// Rein virtuelle Workflow-Markierungen: Start (nur Ausgang) und Abschluss
// (nur Eingang). Sie dienen ausschließlich der Darstellung eines
// vollständigen Ablaufs im Canvas und werden NICHT exportiert
// (negative Typnummer, siehe BlockType#isVirtual).
register(new BlockType(
"start",
"Start",
"Element für den Beginn des Workflows.",
"vaadin:play",
"#16a34a",
START_TASK_TYPE,
0, 1,
List.of()
));
register(new BlockType(
"abschluss",
"Abschluss",
"Element für das Ende des Workflows.",
"vaadin:flag-checkered",
"#b91c1c",
END_TASK_TYPE,
1, 0,
List.of()
));
register(new BlockType( register(new BlockType(
"ankunft-melden", "ankunft-melden",
"Ankunft melden", "Ankunft melden",
"Erfasst die Ankunft am Einsatzort (Bestätigungsschaltfläche).", "Erfasst die Ankunft am Einsatzort (Bestätigungsschaltfläche).",
"vaadin:map-marker", "vaadin:map-marker",
"#2563eb", "#2563eb",
3, 1,
1, 1, 1, 1,
List.of( List.of(
PropertyDefinition.bool("track", "GPS-Position erfassen", true), PropertyDefinition.bool("track", "GPS-Position erfassen", true),
@@ -59,7 +92,7 @@ public class BlockTypeRegistry {
"Nimmt eine Anzahl von Fotos auf.", "Nimmt eine Anzahl von Fotos auf.",
"vaadin:camera", "vaadin:camera",
"#059669", "#059669",
4, 3,
1, 1, 1, 1,
List.of( List.of(
PropertyDefinition.number("min", "Mindestanzahl Fotos", 1), PropertyDefinition.number("min", "Mindestanzahl Fotos", 1),
@@ -69,32 +102,33 @@ public class BlockTypeRegistry {
) )
)); ));
// Fasst die früheren App-Typen Quittungsgeber, Bemerkung und
// Kommissionsnummer zu einem einzigen Texterfassungs-Task zusammen.
register(new BlockType( register(new BlockType(
"quittungsgeber-erfassen", "quittungsgeber-erfassen",
"Quittungsgeber erfassen", "Quittungsgeber erfassen",
"Erfasst den Namen des Quittungsgebers und dessen Anrede aus einer Auswahlliste.", "Erfasst den Quittungsgeber per Eingabefeld.",
"vaadin:user-check", "vaadin:input",
"#dc2626", "#dc2626",
7, 7,
1, 1, 1, 1,
List.of( List.of(
PropertyDefinition.textArea("entries", "Auswahloptionen (eine pro Zeile)"), PropertyDefinition.number("max_len", "Maximale Zeichenanzahl (0 = unbegrenzt)", 0),
PropertyDefinition.number("max_len", "Maximale Zeichenanzahl Name", 40),
PropertyDefinition.bool("opt", "Optionale Aufgabe", false), PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false) PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
) )
)); ));
register(new BlockType( register(new BlockType(
"stationshinweis", "bemerkung-erfassen",
"Stationshinweis", "Bemerkung erfassen",
"sst einen mehrzeiligen Hinweis zur Station erfassen.", "Erfasst eine Bemerkung per Eingabefeld.",
"vaadin:clipboard-text", "vaadin:input",
"#0891b2", "#dc2626",
8, 8,
1, 1, 1, 1,
List.of( List.of(
PropertyDefinition.textArea("txt", "Vorgabetext / Hinweis"), PropertyDefinition.number("max_len", "Maximale Zeichenanzahl (0 = unbegrenzt)", 0),
PropertyDefinition.bool("opt", "Optionale Aufgabe", false), PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false) PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
) )
@@ -103,33 +137,121 @@ public class BlockTypeRegistry {
register(new BlockType( register(new BlockType(
"kommissionsnummer-erfassen", "kommissionsnummer-erfassen",
"Kommissionsnummer erfassen", "Kommissionsnummer erfassen",
"Erfasst eine Kommissionsnummer per Texteingabe.", "Erfasst eine Kommissionsnummer per Eingabefeld.",
"vaadin:hash", "vaadin:abacus",
"#d97706", "#0891b2",
9, 9,
1, 1, 1, 1,
List.of( List.of(
PropertyDefinition.number("max_len", "Maximale Zeichenanzahl", 0), PropertyDefinition.number("max_len", "Maximale Zeichenanzahl (0 = unbegrenzt)", 0),
PropertyDefinition.bool("opt", "Optionale Aufgabe", false), PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false) PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
) )
)); ));
register(new BlockType( register(new BlockType(
"abhol-lieferstatus", "checkbox",
"Abhol-/Lieferstatus", "Checkbox",
"Lässt einen Status aus einer Auswahlliste wählen, optional mit Bemerkung.", "Einfache Bestätigung per Häkchen ohne weitere Eingabe.",
"vaadin:truck", "vaadin:check-square-o",
"#4f46e5", "#16a34a",
11, 6,
1, 1, 1, 1,
List.of( List.of(
PropertyDefinition.textArea("entries", "Statusoptionen (eine pro Zeile)"),
PropertyDefinition.bool("query_remark", "Bemerkung abfragen", false),
PropertyDefinition.bool("opt", "Optionale Aufgabe", false), PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false) PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
) )
)); ));
register(new BlockType(
"barcode-scannen",
"Barcode scannen",
"Erfasst eine Liste gescannter Barcodes. (In der Flutter-App deaktiviert.)",
"vaadin:barcode",
"#0d9488",
5,
1, 1,
List.of(
PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
)
));
// Vereint den früheren "Status" und "Abhol-/Lieferstatus" der App
// zu einer Status-Auswahlliste auf Basis der choices-Struktur.
register(new BlockType(
"statusauswahl",
"Statusauswahl",
"Lässt einen Status aus einer Auswahlliste wählen.",
"vaadin:list-select",
"#ea580c",
11,
1, 1,
List.of(
PropertyDefinition.choiceList("choices", "Statusoptionen"),
PropertyDefinition.bool("opt", "Optionale Aufgabe", false),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
)
));
// Listen-Tasks: erfassen mehrerer gleichartiger Werte. Die Anzahl wird
// analog zu "Fotos aufnehmen" über min/max gesteuert. Diese Typen haben
// (noch) keinen Handler in der stadtbote-App und liegen daher oberhalb
// des dort genutzten Bereichs (111).
register(new BlockType(
"text-liste-erfassen",
"Liste von Texten erfassen",
"Erfasst mehrere Texteinträge über vordefinierte Eingabefelder.",
"vaadin:lines-list",
"#4338ca",
12,
1, 1,
List.of(
PropertyDefinition.fieldList("fields", "Textfelder (Titel + Platzhalter)"),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
)
));
register(new BlockType(
"zahl-liste-erfassen",
"Liste von Zahlen erfassen",
"Erfasst mehrere numerische Werte über vordefinierte Eingabefelder.",
"vaadin:list-ol",
"#0369a1",
13,
1, 1,
List.of(
PropertyDefinition.fieldList("fields", "Zahlenfelder (Titel + Platzhalter)"),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
)
));
register(new BlockType(
"checkbox-liste-erfassen",
"Liste von Checkboxen erfassen",
"Lässt mehrere vordefinierte Optionen per Checkbox ankreuzen.",
"vaadin:tasks",
"#15803d",
14,
1, 1,
List.of(
PropertyDefinition.nameList("entries", "Name der Checkboxen"),
PropertyDefinition.bool("reenter", "Erneut bearbeitbar", false)
)
));
if (!hideScriptBlock) {
register(new BlockType(
"script",
"Script",
"Kleines Logik-Snippet grafisch zusammenstellen (if/else, Vergleiche …).",
"vaadin:code",
"#475569",
0,
1, 0,
List.of()
));
}
} }
private void register(BlockType type) { private void register(BlockType type) {
@@ -143,4 +265,79 @@ public class BlockTypeRegistry {
public Optional<BlockType> find(String id) { public Optional<BlockType> find(String id) {
return Optional.ofNullable(types.get(id)); return Optional.ofNullable(types.get(id));
} }
/** Die festen Standard-Typen (Typnummer 18), auf denen eigene Typen aufbauen. */
public List<BlockType> baseTypes() {
return types.values().stream()
.filter(t -> t.taskType() >= 1 && t.taskType() < CUSTOM_TYPE_START)
.toList();
}
/** Startwert für benutzerdefinierte Typnummern. */
public static final int CUSTOM_TYPE_START = 1000;
/** Nächste freie Typnummer ab {@value #CUSTOM_TYPE_START}. */
public synchronized int nextCustomTaskType() {
int next = CUSTOM_TYPE_START;
for (BlockType type : types.values()) {
if (type.taskType() >= next) {
next = type.taskType() + 1;
}
}
return next;
}
/**
* Legt einen benutzerdefinierten Typ an. Er übernimmt Aussehen, Ein-/Ausgänge
* und Eigenschaftsstruktur des Basis-Typs, erhält aber eine eigene Typnummer
* ({@code >= 1000}) und eine eigene Bezeichnung.
*
* @param taskType die (freie) Typnummer
* @param base der zugrunde liegende Standard-Typ
* @param label Bezeichnung des neuen Typs
* @param properties Eigenschaften (i. d. R. die des Basis-Typs mit erfassten Vorgaben)
*/
public synchronized BlockType registerCustom(int taskType, BlockType base, String label,
List<PropertyDefinition> properties) {
String id = "custom-" + taskType;
BlockType custom = new BlockType(
id,
label,
base.description(),
base.icon(),
base.color(),
taskType,
base.inputs(),
base.outputs(),
List.copyOf(properties),
base.id()
);
register(custom);
return custom;
}
/**
* Registriert einen bereits vollständig aufgebauten benutzerdefinierten Typ
* (z. B. aus MongoDB geladen). Bereits vorhandene Typen mit gleicher ID
* werden überschrieben.
*/
public synchronized BlockType registerCustom(BlockType custom) {
register(custom);
return custom;
}
/**
* Entfernt einen benutzerdefinierten Typ (Typnummer {@code >= 1000}).
* Feste Standard-Typen werden nicht entfernt.
*
* @return {@code true}, wenn ein benutzerdefinierter Typ entfernt wurde
*/
public synchronized boolean removeCustom(String id) {
BlockType existing = types.get(id);
if (existing == null || existing.taskType() < CUSTOM_TYPE_START) {
return false;
}
types.remove(id);
return true;
}
} }

View File

@@ -0,0 +1,82 @@
package de.assecutor.tasklisteditor.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* Eine Auswahloption eines Status-Tasks (Typ 6).
* Entspricht {@code Choice} der stadtbote-App.
*
* <p>Die Feldnamen sind klein geschrieben; die App deserialisiert per
* Newtonsoft case-insensitiv (txt, ret, term, quest, action, price).
* {@code null}-Felder (quest, price) werden ausgelassen.
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"txt", "ret", "term", "quest", "action", "price"})
public class ChoiceDto {
private String txt;
private int ret;
private boolean term;
private String quest;
private String action;
private String price;
public ChoiceDto() {
}
public ChoiceDto(String txt, int ret) {
this.txt = txt;
this.ret = ret;
this.term = false;
this.action = "cont";
}
public String getTxt() {
return txt;
}
public void setTxt(String txt) {
this.txt = txt;
}
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public boolean isTerm() {
return term;
}
public void setTerm(boolean term) {
this.term = term;
}
public String getQuest() {
return quest;
}
public void setQuest(String quest) {
this.quest = quest;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}

View File

@@ -0,0 +1,64 @@
package de.assecutor.tasklisteditor.model;
/**
* In MongoDB ablegbarer Zustand einer {@link PropertyDefinition} eines
* benutzerdefinierten Typs (inkl. der erfassten Vorgabe). Beim Laden wird
* daraus wieder eine {@link PropertyDefinition} aufgebaut.
*/
public class CustomPropertyState {
private String id;
private String label;
private PropertyType type;
private Object defaultValue;
public CustomPropertyState() {
}
public CustomPropertyState(String id, String label, PropertyType type, Object defaultValue) {
this.id = id;
this.label = label;
this.type = type;
this.defaultValue = defaultValue;
}
public static CustomPropertyState of(PropertyDefinition def) {
return new CustomPropertyState(def.id(), def.label(), def.type(), def.defaultValue());
}
public PropertyDefinition toDefinition() {
return new PropertyDefinition(id, label, type, defaultValue);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public PropertyType getType() {
return type;
}
public void setType(PropertyType type) {
this.type = type;
}
public Object getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(Object defaultValue) {
this.defaultValue = defaultValue;
}
}

View File

@@ -0,0 +1,52 @@
package de.assecutor.tasklisteditor.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* Ein einzelnes Eingabefeld eines Listen-Text-Tasks (Typ 12).
* 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", "required"})
public class FieldDto {
private String title;
private String placeholder;
private Boolean required;
public FieldDto() {
}
public FieldDto(String title, String placeholder) {
this.title = title;
this.placeholder = placeholder;
}
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPlaceholder() {
return placeholder;
}
public void setPlaceholder(String placeholder) {
this.placeholder = placeholder;
}
}

View File

@@ -1,5 +1,7 @@
package de.assecutor.tasklisteditor.model; package de.assecutor.tasklisteditor.model;
import java.util.List;
public record PropertyDefinition(String id, String label, PropertyType type, Object defaultValue) { public record PropertyDefinition(String id, String label, PropertyType type, Object defaultValue) {
public static PropertyDefinition text(String id, String label) { public static PropertyDefinition text(String id, String label) {
return new PropertyDefinition(id, label, PropertyType.TEXT, ""); return new PropertyDefinition(id, label, PropertyType.TEXT, "");
@@ -16,4 +18,16 @@ public record PropertyDefinition(String id, String label, PropertyType type, Obj
public static PropertyDefinition bool(String id, String label, boolean defaultValue) { public static PropertyDefinition bool(String id, String label, boolean defaultValue) {
return new PropertyDefinition(id, label, PropertyType.BOOLEAN, defaultValue); return new PropertyDefinition(id, label, PropertyType.BOOLEAN, defaultValue);
} }
public static PropertyDefinition fieldList(String id, String label) {
return new PropertyDefinition(id, label, PropertyType.FIELD_LIST, List.of());
}
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());
}
} }

View File

@@ -4,5 +4,14 @@ public enum PropertyType {
TEXT, TEXT,
TEXTAREA, TEXTAREA,
NUMBER, NUMBER,
BOOLEAN BOOLEAN,
/** Wiederholbare Liste aus Eingabefeldern mit Titel und Platzhalter. */
FIELD_LIST,
/** Wiederholbare Liste aus reinen Namens-Einträgen (ein Textfeld je Zeile). */
NAME_LIST,
/**
* Wiederholbare Liste aus Auswahloptionen (ein Textfeld je Zeile,
* ohne Pflichtfeld-Kennzeichen).
*/
CHOICE_LIST
} }

View File

@@ -3,6 +3,7 @@ package de.assecutor.tasklisteditor.model;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.JsonNode;
import java.util.List; import java.util.List;
@@ -16,7 +17,7 @@ import java.util.List;
*/ */
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({"s_id", "type", "topic", "opt", "reenter", "min", "max", @JsonPropertyOrder({"s_id", "type", "topic", "opt", "reenter", "min", "max",
"max_len", "rt", "track", "txt", "task_arrival", "task_fin_work", "entries"}) "max_len", "rt", "track", "txt", "task_arrival", "task_fin_work", "entries", "choices", "fields", "script"})
public class TaskDto { public class TaskDto {
@JsonProperty("s_id") @JsonProperty("s_id")
@@ -46,6 +47,15 @@ public class TaskDto {
private List<TaskEntryDto> entries; private List<TaskEntryDto> entries;
/** Auswahloptionen eines Status-Tasks (Typ 6). */
private List<ChoiceDto> choices;
/** Eingabefelder eines Listen-Text-Tasks (Typ 12). */
private List<FieldDto> fields;
/** Logik-Graph eines Script-Blocks (Drawflow-Definition als JSON). */
private JsonNode script;
public int getSId() { public int getSId() {
return sId; return sId;
} }
@@ -157,4 +167,28 @@ public class TaskDto {
public void setEntries(List<TaskEntryDto> entries) { public void setEntries(List<TaskEntryDto> entries) {
this.entries = entries; this.entries = entries;
} }
public List<ChoiceDto> getChoices() {
return choices;
}
public void setChoices(List<ChoiceDto> choices) {
this.choices = choices;
}
public List<FieldDto> getFields() {
return fields;
}
public void setFields(List<FieldDto> fields) {
this.fields = fields;
}
public JsonNode getScript() {
return script;
}
public void setScript(JsonNode script) {
this.script = script;
}
} }

View File

@@ -1,5 +1,6 @@
package de.assecutor.tasklisteditor.model; package de.assecutor.tasklisteditor.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** /**
@@ -14,6 +15,10 @@ public class TaskEntryDto {
@JsonProperty("query_remark") @JsonProperty("query_remark")
private boolean queryRemark; private boolean queryRemark;
/** Pflichtfeld-Kennzeichen (nur bei Listen-Tasks gesetzt, sonst ausgelassen). */
@JsonInclude(JsonInclude.Include.NON_NULL)
private Boolean required;
public TaskEntryDto() { public TaskEntryDto() {
} }
@@ -46,4 +51,12 @@ public class TaskEntryDto {
public void setQueryRemark(boolean queryRemark) { public void setQueryRemark(boolean queryRemark) {
this.queryRemark = queryRemark; this.queryRemark = queryRemark;
} }
public Boolean getRequired() {
return required;
}
public void setRequired(Boolean required) {
this.required = required;
}
} }

View File

@@ -0,0 +1,16 @@
package de.assecutor.tasklisteditor.repository;
import de.assecutor.tasklisteditor.document.CustomTypeDocument;
import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;
/**
* Spring-Data-Repository für die in MongoDB abgelegten benutzerdefinierten Typen.
*/
public interface CustomTypeRepository extends MongoRepository<CustomTypeDocument, String> {
List<CustomTypeDocument> findAllByOrderByTaskTypeAsc();
long deleteByTaskType(int taskType);
}

View File

@@ -0,0 +1,73 @@
package de.assecutor.tasklisteditor.service;
import de.assecutor.tasklisteditor.document.CustomTypeDocument;
import de.assecutor.tasklisteditor.model.BlockType;
import de.assecutor.tasklisteditor.model.CustomPropertyState;
import de.assecutor.tasklisteditor.repository.CustomTypeRepository;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.List;
/**
* Speichert benutzerdefinierte Typen in MongoDB und stellt sie als
* {@link BlockType} wieder her.
*/
@Service
public class CustomTypeService {
private final CustomTypeRepository repository;
public CustomTypeService(CustomTypeRepository repository) {
this.repository = repository;
}
/** Persistiert einen benutzerdefinierten Typ mit allen Daten. */
public String save(BlockType custom, String baseTypeId) {
CustomTypeDocument document = new CustomTypeDocument();
document.setTaskType(custom.taskType());
document.setTypeId(custom.id());
document.setLabel(custom.label());
document.setBaseTypeId(baseTypeId);
document.setDescription(custom.description());
document.setIcon(custom.icon());
document.setColor(custom.color());
document.setInputs(custom.inputs());
document.setOutputs(custom.outputs());
document.setProperties(custom.properties().stream()
.map(CustomPropertyState::of)
.toList());
document.setCreatedAt(Instant.now());
return repository.save(document).getId();
}
/** Löscht den gespeicherten benutzerdefinierten Typ mit der angegebenen Typnummer. */
public void deleteByTaskType(int taskType) {
repository.deleteByTaskType(taskType);
}
/** Lädt alle gespeicherten Typen und baut sie als {@link BlockType} auf. */
public List<BlockType> loadAll() {
return repository.findAllByOrderByTaskTypeAsc().stream()
.map(CustomTypeService::toBlockType)
.toList();
}
private static BlockType toBlockType(CustomTypeDocument doc) {
return new BlockType(
doc.getTypeId(),
doc.getLabel(),
doc.getDescription(),
doc.getIcon(),
doc.getColor(),
doc.getTaskType(),
doc.getInputs(),
doc.getOutputs(),
doc.getProperties() == null ? List.of()
: doc.getProperties().stream()
.map(prop -> prop.toDefinition())
.toList(),
doc.getBaseTypeId()
);
}
}

View File

@@ -0,0 +1,70 @@
package de.assecutor.tasklisteditor.service;
import de.assecutor.tasklisteditor.config.ElementCollectionProperties;
import de.assecutor.tasklisteditor.document.ElementSettingsDocument;
import de.assecutor.tasklisteditor.model.BlockInstance;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.util.Collection;
import java.util.LinkedHashMap;
/**
* Speichert die Einstellungen der einzelnen platzierten Elemente eines Canvas
* jeweils in einer eigenen, pro Element-Typ konfigurierten MongoDB-Collection.
*
* <p>Wird ergänzend zum {@link CanvasService} aufgerufen: Der Canvas-Stand
* (Layout + Block-Werte) bleibt unverändert im Canvas-Dokument; zusätzlich wird
* je Element ein {@link ElementSettingsDocument} in die Typ-Collection
* geschrieben und über die Canvas-ID verknüpft.
*/
@Service
public class ElementSettingsService {
private final MongoTemplate mongoTemplate;
private final ElementCollectionProperties properties;
public ElementSettingsService(MongoTemplate mongoTemplate,
ElementCollectionProperties properties) {
this.mongoTemplate = mongoTemplate;
this.properties = properties;
}
/**
* Schreibt für jedes Element des Canvas ein Einstellungs-Dokument in die
* Collection seines Typs.
*
* @param canvasId ID des gespeicherten Canvas (Verknüpfung)
* @param canvasName Anzeigename des Canvas
* @param instances platzierte Block-Instanzen
*/
public void saveForCanvas(String canvasId, String canvasName,
Collection<BlockInstance> instances) {
Instant now = Instant.now();
for (BlockInstance instance : instances) {
// Virtuelle Blöcke (Start/Abschluss) haben keine fachlichen
// Einstellungen und keine Collection sie werden nicht persistiert.
if (instance.type().isVirtual()) {
continue;
}
String typeId = instance.type().id();
String baseTypeId = instance.type().baseTypeId();
// Benutzerdefinierte Typen landen in der Collection ihres statischen
// Basistyps; feste Typen (baseTypeId == null) in ihrer eigenen.
String collectionTypeId = (baseTypeId == null || baseTypeId.isBlank())
? typeId
: baseTypeId;
ElementSettingsDocument document = new ElementSettingsDocument(
canvasId,
canvasName,
instance.id(),
typeId,
baseTypeId,
instance.topic(),
new LinkedHashMap<>(instance.values()),
now);
mongoTemplate.save(document, properties.collectionFor(collectionTypeId));
}
}
}

View File

@@ -3,6 +3,9 @@ package de.assecutor.tasklisteditor.service;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import de.assecutor.tasklisteditor.model.BlockInstance; import de.assecutor.tasklisteditor.model.BlockInstance;
import de.assecutor.tasklisteditor.model.BlockTypeRegistry;
import de.assecutor.tasklisteditor.model.ChoiceDto;
import de.assecutor.tasklisteditor.model.FieldDto;
import de.assecutor.tasklisteditor.model.TaskDto; import de.assecutor.tasklisteditor.model.TaskDto;
import de.assecutor.tasklisteditor.model.TaskEntryDto; import de.assecutor.tasklisteditor.model.TaskEntryDto;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@@ -35,6 +38,22 @@ public class TaskListExporter {
} }
public List<TaskDto> export(String drawflowJson, Map<Integer, BlockInstance> instances) { 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<>(); List<TaskDto> tasks = new ArrayList<>();
if (drawflowJson == null || drawflowJson.isBlank()) { if (drawflowJson == null || drawflowJson.isBlank()) {
return tasks; return tasks;
@@ -46,6 +65,12 @@ public class TaskListExporter {
} catch (Exception ex) { } catch (Exception ex) {
throw new IllegalStateException("Editor-Graph konnte nicht gelesen werden: " + ex.getMessage(), ex); throw new IllegalStateException("Editor-Graph konnte nicht gelesen werden: " + ex.getMessage(), ex);
} }
// Ein vollständiger Workflow muss mit einem Start- und einem Abschluss-
// Element gerahmt und beide müssen verdrahtet sein.
if (!forAssistant) {
validateWorkflow(data, instances);
}
if (!data.isObject() || data.isEmpty()) { if (!data.isObject() || data.isEmpty()) {
return tasks; return tasks;
} }
@@ -58,6 +83,11 @@ public class TaskListExporter {
if (instance == null) { if (instance == null) {
continue; continue;
} }
// Rein virtuelle Blöcke (Start/Abschluss) sind nur Workflow-Markierungen
// und gehören nicht in die exportierte Task-Liste.
if (!forAssistant && instance.type().isVirtual()) {
continue;
}
TaskDto task = toTask(instance); TaskDto task = toTask(instance);
task.setSId(sId++); task.setSId(sId++);
tasks.add(task); tasks.add(task);
@@ -65,6 +95,74 @@ public class TaskListExporter {
return tasks; return tasks;
} }
/**
* Stellt sicher, dass der Ablauf mit genau den virtuellen Markierungen
* gerahmt ist: Es muss mindestens ein Start- und ein Abschluss-Element
* geben und beide müssen mit dem Ablauf verbunden (verdrahtet) sein.
*
* @throws IllegalStateException mit einer für den Benutzer verständlichen
* Meldung, falls die Bedingung verletzt ist
*/
private void validateWorkflow(JsonNode data, Map<Integer, BlockInstance> instances) {
// Es muss mindestens ein Start- und ein Abschluss-Element geben.
boolean hasStart = false;
boolean hasEnd = false;
for (BlockInstance instance : instances.values()) {
int taskType = instance.type().taskType();
if (taskType == BlockTypeRegistry.START_TASK_TYPE) {
hasStart = true;
} else if (taskType == BlockTypeRegistry.END_TASK_TYPE) {
hasEnd = true;
}
}
if (!hasStart) {
throw new IllegalStateException("Es muss ein Start-Element vorhanden sein.");
}
if (!hasEnd) {
throw new IllegalStateException("Es muss ein Abschluss-Element vorhanden sein.");
}
// Jedes Element muss vollständig verdrahtet sein: jeder vorhandene Ein-
// und Ausgang muss mit mindestens einer Linie belegt sein. Start besitzt
// nur einen Ausgang, Abschluss nur einen Eingang nicht vorhandene Ports
// werden dabei nicht gefordert.
List<String> nodeIds = new ArrayList<>();
data.fieldNames().forEachRemaining(nodeIds::add);
for (String nodeId : nodeIds) {
JsonNode node = data.path(nodeId);
if (!allPortsConnected(node.path("inputs")) || !allPortsConnected(node.path("outputs"))) {
throw new IllegalStateException(
"Jedes Element muss vollständig verbunden sein "
+ nodeLabel(instances, nodeId)
+ "“ hat einen offenen Ein- oder Ausgang.");
}
}
}
/** Prüft, ob alle vorhandenen Ports (Ein- oder Ausgänge) mindestens eine Verbindung haben. */
private boolean allPortsConnected(JsonNode ports) {
for (JsonNode port : ports) {
if (port.path("connections").size() == 0) {
return false;
}
}
return true;
}
/** Liefert einen sprechenden Namen eines Knotens für Fehlermeldungen. */
private String nodeLabel(Map<Integer, BlockInstance> instances, String nodeId) {
try {
BlockInstance instance = instances.get(Integer.parseInt(nodeId));
if (instance != null) {
String topic = instance.topic();
return (topic == null || topic.isBlank()) ? instance.type().label() : topic;
}
} catch (NumberFormatException ignored) {
// Fällt auf die Knoten-ID zurück.
}
return "#" + nodeId;
}
private List<Integer> determineOrder(JsonNode data) { private List<Integer> determineOrder(JsonNode data) {
// Knoten einsammeln + eingehende Verbindungen zählen. // Knoten einsammeln + eingehende Verbindungen zählen.
List<Integer> nodeIds = new ArrayList<>(); List<Integer> nodeIds = new ArrayList<>();
@@ -143,7 +241,32 @@ public class TaskListExporter {
if (v.containsKey("entries")) { if (v.containsKey("entries")) {
boolean queryRemark = v.containsKey("query_remark") && asBool(v.get("query_remark")); boolean queryRemark = v.containsKey("query_remark") && asBool(v.get("query_remark"));
task.setEntries(parseEntries(asText(v.get("entries")), queryRemark)); Object raw = v.get("entries");
task.setEntries(raw instanceof List<?> list
? parseEntries(list, queryRemark)
: parseEntries(asText(raw), queryRemark));
}
if (v.containsKey("choices")) {
Object raw = v.get("choices");
task.setChoices(raw instanceof List<?> list
? parseChoices(list)
: parseChoices(asText(raw)));
}
if (v.containsKey("fields")) {
task.setFields(parseFields(v.get("fields")));
}
if (v.containsKey("script")) {
String script = asText(v.get("script"));
if (script != null) {
try {
task.setScript(objectMapper.readTree(script));
} catch (Exception ignored) {
// Ungültiges Skript-JSON wird ausgelassen.
}
}
} }
return task; return task;
} }
@@ -163,6 +286,72 @@ public class TaskListExporter {
return entries.isEmpty() ? null : entries; return entries.isEmpty() ? null : entries;
} }
/** Variante für den Zeilen-Editor: Liste aus {@code {title}}-Einträgen. */
private List<TaskEntryDto> parseEntries(List<?> raw, boolean queryRemark) {
List<TaskEntryDto> entries = new ArrayList<>();
int code = 1;
for (Object o : raw) {
if (o instanceof Map<?, ?> m) {
String text = m.get("title") == null ? "" : m.get("title").toString().trim();
if (!text.isEmpty()) {
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;
}
List<ChoiceDto> choices = new ArrayList<>();
int ret = 1;
for (String line : raw.split("\\r?\\n")) {
String text = line.trim();
if (!text.isEmpty()) {
choices.add(new ChoiceDto(text, ret++));
}
}
return choices.isEmpty() ? null : choices;
}
private List<FieldDto> parseFields(Object raw) {
if (!(raw instanceof List<?> list) || list.isEmpty()) {
return null;
}
List<FieldDto> fields = new ArrayList<>();
for (Object o : list) {
if (o instanceof Map<?, ?> m) {
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()) {
FieldDto field = new FieldDto(title, placeholder);
field.setRequired(asBool(m.get("required")));
fields.add(field);
}
}
}
return fields.isEmpty() ? null : fields;
}
private Boolean asBool(Object o) { private Boolean asBool(Object o) {
return o instanceof Boolean b ? b : Boolean.parseBoolean(String.valueOf(o)); return o instanceof Boolean b ? b : Boolean.parseBoolean(String.valueOf(o));
} }

View File

@@ -2,6 +2,8 @@ package de.assecutor.tasklisteditor.service;
import de.assecutor.tasklisteditor.model.BlockType; import de.assecutor.tasklisteditor.model.BlockType;
import de.assecutor.tasklisteditor.model.BlockTypeRegistry; 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.PropertyDefinition;
import de.assecutor.tasklisteditor.model.TaskDto; import de.assecutor.tasklisteditor.model.TaskDto;
import de.assecutor.tasklisteditor.model.TaskEntryDto; import de.assecutor.tasklisteditor.model.TaskEntryDto;
@@ -62,31 +64,91 @@ public class TaskListImporter {
private Map<String, Object> valuesFor(BlockType type, TaskDto task) { private Map<String, Object> valuesFor(BlockType type, TaskDto task) {
Map<String, Object> values = new LinkedHashMap<>(); Map<String, Object> values = new LinkedHashMap<>();
for (PropertyDefinition def : type.properties()) { for (PropertyDefinition def : type.properties()) {
Object value = switch (def.id()) { // Listen-Eigenschaften (Typ 1214) werden anhand ihres
case "opt" -> orDefault(task.getOpt(), def.defaultValue()); // Property-Typs in die vom Zeilen-Editor erwartete Struktur
case "reenter" -> orDefault(task.getReenter(), def.defaultValue()); // (Liste aus {title}/{title,placeholder}-Maps) zurückgewandelt.
case "rt" -> orDefault(task.getRt(), def.defaultValue()); Object value = switch (def.type()) {
case "track" -> orDefault(task.getTrack(), def.defaultValue()); case FIELD_LIST -> fieldRows(task);
case "min" -> orDefault(task.getMin(), def.defaultValue()); case NAME_LIST -> entryRows(task);
case "max" -> orDefault(task.getMax(), def.defaultValue()); case CHOICE_LIST -> choiceRows(task);
case "max_len" -> orDefault(task.getMaxLen(), def.defaultValue()); default -> scalarValue(def, task);
case "txt" -> orDefault(task.getTxt(), def.defaultValue());
case "query_remark" -> anyQueryRemark(task);
case "entries" -> entriesText(task);
default -> def.defaultValue();
}; };
values.put(def.id(), value); values.put(def.id(), value);
} }
return values; return values;
} }
private Object scalarValue(PropertyDefinition def, TaskDto task) {
return switch (def.id()) {
case "opt" -> orDefault(task.getOpt(), def.defaultValue());
case "reenter" -> orDefault(task.getReenter(), def.defaultValue());
case "rt" -> orDefault(task.getRt(), def.defaultValue());
case "track" -> orDefault(task.getTrack(), def.defaultValue());
case "min" -> orDefault(task.getMin(), def.defaultValue());
case "max" -> orDefault(task.getMax(), def.defaultValue());
case "max_len" -> orDefault(task.getMaxLen(), def.defaultValue());
case "txt" -> orDefault(task.getTxt(), def.defaultValue());
case "query_remark" -> anyQueryRemark(task);
case "entries" -> entriesText(task);
case "choices" -> choicesText(task);
default -> def.defaultValue();
};
}
/** {@code fields}-Array (Typ 12/13) zurück in Zeilen mit Titel + Platzhalter. */
private List<Map<String, Object>> fieldRows(TaskDto task) {
List<Map<String, Object>> rows = new ArrayList<>();
if (task.getFields() == null) {
return rows;
}
for (FieldDto field : task.getFields()) {
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;
}
/** {@code entries}-Array (Typ 14) zurück in Zeilen mit Namen ({@code title}). */
private List<Map<String, Object>> entryRows(TaskDto task) {
List<Map<String, Object>> rows = new ArrayList<>();
if (task.getEntries() == null) {
return rows;
}
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) { private Object orDefault(Object value, Object fallback) {
return value != null ? value : fallback; return value != null ? value : fallback;
} }
private boolean anyQueryRemark(TaskDto task) { private boolean anyQueryRemark(TaskDto task) {
return task.getEntries() != null return task.getEntries() != null
&& task.getEntries().stream().anyMatch(TaskEntryDto::isQueryRemark); && task.getEntries().stream().anyMatch(entry -> entry.isQueryRemark());
} }
private String entriesText(TaskDto task) { private String entriesText(TaskDto task) {
@@ -94,7 +156,18 @@ public class TaskListImporter {
return ""; return "";
} }
return task.getEntries().stream() return task.getEntries().stream()
.map(TaskEntryDto::getText) .map(entry -> entry.getText())
.collect(Collectors.joining("\n")); .collect(Collectors.joining("\n"));
} }
private String choicesText(TaskDto task) {
if (task.getChoices() != null && !task.getChoices().isEmpty()) {
return task.getChoices().stream()
.map(choice -> choice.getTxt())
.collect(Collectors.joining("\n"));
}
// Altdaten des früheren Typ 11 (Abhol-/Lieferstatus) liefern die Optionen
// als entries; diese als choices-Text übernehmen.
return entriesText(task);
}
} }

View File

@@ -9,6 +9,7 @@ import de.assecutor.tasklisteditor.repository.TaskListRepository;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.time.Instant; import java.time.Instant;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -31,10 +32,20 @@ public class TaskListService {
this.objectMapper = objectMapper; this.objectMapper = objectMapper;
} }
/**
* Task-Typ des Script-Blocks (siehe {@code BlockTypeRegistry}) wird von der
* stadtbote-App nicht verarbeitet und daher aus dem App-JSON ausgelassen.
*/
private static final int SCRIPT_TASK_TYPE = 0;
/** Ergebnis eines Exports: typisierte Tasks plus formatiertes JSON. */ /** Ergebnis eines Exports: typisierte Tasks plus formatiertes JSON. */
public record ExportResult(List<TaskDto> tasks, String json) { public record ExportResult(List<TaskDto> tasks, String json) {
} }
/** Ergebnis eines App-Job-Exports: Anzahl Tasks plus formatiertes Job-JSON. */
public record AppJobResult(int taskCount, String json) {
}
public ExportResult build(String drawflowJson, Map<Integer, BlockInstance> instances) { public ExportResult build(String drawflowJson, Map<Integer, BlockInstance> instances) {
List<TaskDto> tasks = exporter.export(drawflowJson, instances); List<TaskDto> tasks = exporter.export(drawflowJson, instances);
try { try {
@@ -45,6 +56,52 @@ 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).
*
* <p>Script-Blöcke (Typ 100) werden ausgelassen, da die App sie nicht
* verarbeitet; anschließend werden die {@code s_id}-Werte lückenlos neu
* vergeben.
*
* @param name nicht verwendet (bleibt für künftige Erweiterungen erhalten)
*/
public AppJobResult buildAppJob(String name, String drawflowJson,
Map<Integer, BlockInstance> instances) {
List<TaskDto> tasks = new ArrayList<>();
int sId = 1;
for (TaskDto task : exporter.export(drawflowJson, instances)) {
if (task.getType() == SCRIPT_TASK_TYPE) {
continue;
}
task.setScript(null);
task.setSId(sId++);
tasks.add(task);
}
try {
String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(tasks);
return new AppJobResult(tasks.size(), json);
} catch (JsonProcessingException ex) {
throw new IllegalStateException("App-JSON konnte nicht erzeugt werden: " + ex.getMessage(), ex);
}
}
/** /**
* Speichert die Task-Liste in MongoDB. * Speichert die Task-Liste in MongoDB.
* *

View File

@@ -0,0 +1,279 @@
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 boolean aiEnabled;
private final String apiKey;
private final String model;
private final ObjectMapper lenientMapper;
private volatile AnthropicClient client;
public WorkflowAssistantService(BlockTypeRegistry registry,
@Value("${tasklist.ai-enabled:false}") boolean aiEnabled,
@Value("${tasklist.anthropic-api-key:}") String apiKey,
@Value("${tasklist.anthropic-model:claude-opus-4-8}") String model) {
this.registry = registry;
this.aiEnabled = aiEnabled;
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 (AI_ENABLED=true und API-Key in der .env). */
public boolean isEnabled() {
return aiEnabled && !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(
"KI-Assistent deaktiviert: AI_ENABLED=true und ANTHROPIC_API_KEY "
+ "in der .env-Datei setzen.");
}
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);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,9 @@
server.port=8080 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.launch-browser=true
vaadin.allowed-packages=de.assecutor.tasklisteditor vaadin.allowed-packages=de.assecutor.tasklisteditor
@@ -16,6 +20,39 @@ logging.level.org.atmosphere=WARN
# startet auch ohne laufende MongoDB. # startet auch ohne laufende MongoDB.
spring.data.mongodb.uri=${MONGODB_URI:mongodb://localhost:27017} spring.data.mongodb.uri=${MONGODB_URI:mongodb://localhost:27017}
spring.data.mongodb.database=${MONGODB_DATABASE:tasklist_editor} spring.data.mongodb.database=${MONGODB_DATABASE:tasklist_editor}
# Legt die @Indexed-Indizes (u. a. eindeutige Typnummer) bei Bedarf an.
spring.data.mongodb.auto-index-creation=true
# Health-Check soll nicht fehlschlagen, wenn keine MongoDB läuft. # Health-Check soll nicht fehlschlagen, wenn keine MongoDB läuft.
management.health.mongo.enabled=false management.health.mongo.enabled=false
# Script-Block (grafisches Logik-Element) im Editor ausblenden.
# Wird per .env (HIDE_SCRIPT_BLOCK) gesteuert.
tasklist.hide-script-block=${HIDE_SCRIPT_BLOCK:false}
# --- KI-Workflow-Assistent (Claude API) --------------------------------------
# Ein-/Ausschalter, API-Key und Modell kommen aus der .env-Datei (AI_ENABLED,
# ANTHROPIC_API_KEY, ANTHROPIC_MODEL). Der Assistent ist nur verfügbar, wenn
# AI_ENABLED=true gesetzt UND ein Key hinterlegt ist (Standard: aus).
tasklist.ai-enabled=${AI_ENABLED:false}
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
# (MONGODB_ELEMENT_*), mit Default. Benutzerdefinierte Typen werden auf ihren
# statischen Basistyp aufgelöst; für jeden Typ muss eine Zuordnung existieren.
tasklist.element-collections[ankunft-melden]=${MONGODB_ELEMENT_ARRIVAL_COLLECTION:element_arrival}
tasklist.element-collections[unterschrift-erfassen]=${MONGODB_ELEMENT_SIGNATURE_COLLECTION:element_signature}
tasklist.element-collections[fotos-aufnehmen]=${MONGODB_ELEMENT_PHOTOS_COLLECTION:element_photos}
tasklist.element-collections[quittungsgeber-erfassen]=${MONGODB_ELEMENT_RECEIPT_GIVER_COLLECTION:element_receipt_giver}
tasklist.element-collections[bemerkung-erfassen]=${MONGODB_ELEMENT_REMARK_COLLECTION:element_remark}
tasklist.element-collections[kommissionsnummer-erfassen]=${MONGODB_ELEMENT_COMMISSION_NUMBER_COLLECTION:element_commission_number}
tasklist.element-collections[checkbox]=${MONGODB_ELEMENT_CHECKBOX_COLLECTION:element_checkbox}
tasklist.element-collections[barcode-scannen]=${MONGODB_ELEMENT_BARCODE_COLLECTION:element_barcode}
tasklist.element-collections[statusauswahl]=${MONGODB_ELEMENT_STATUS_SELECTION_COLLECTION:element_status_selection}
tasklist.element-collections[text-liste-erfassen]=${MONGODB_ELEMENT_TEXT_LIST_COLLECTION:element_text_list}
tasklist.element-collections[zahl-liste-erfassen]=${MONGODB_ELEMENT_NUMBER_LIST_COLLECTION:element_number_list}
tasklist.element-collections[checkbox-liste-erfassen]=${MONGODB_ELEMENT_CHECKBOX_LIST_COLLECTION:element_checkbox_list}
tasklist.element-collections[script]=${MONGODB_ELEMENT_SCRIPT_COLLECTION:element_script}