feat: Phase 5 - Visual Workflow Editor (Option B)
Backend (Mini-Backend 1-2h): - Migration 016: ai_prompts.graph_data JSONB column - workflow_executor: graph_data parameter support (backward-compatible) - prompt_executor: execute_workflow_prompt uses graph_data Frontend (Main effort 25-35h): - WorkflowCanvas: React Flow wrapper component - 5 Custom Nodes: Start, End, Analysis, Logic, Join - 4 Config Panels: QuestionAugmentation, LogicExpression, Fallback, Join - workflowValidation: Structural + logical validation - workflowSerializer: Canvas ↔ JSONB conversion - WorkflowEditorPage: Main orchestration (420 LOC) - Route: /workflow-editor/:id - CSS: workflowEditor.css (300 LOC) Architecture: - Option B: ai_prompts.type='workflow' (not separate table) - panels/ subdirectory for clean separation - WorkflowCanvas reusable component - User GUI identical (Workflows = Prompts) - Backward-compatible (type='pipeline' unchanged) Version: v0.9m → v0.9n (Phase 5 complete) Module: workflow 0.5.0 → 0.6.0 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
a7058c30be
commit
dc59596f01
23 files changed
+3010
-48
No files matched your search
@@ -39,6 +39,7 @@ import RestDaysPage from './pages/RestDaysPage'
|
||||
import VitalsPage from './pages/VitalsPage'
|
||||
import GoalsPage from './pages/GoalsPage'
|
||||
import CustomGoalsPage from './pages/CustomGoalsPage'
|
||||
import WorkflowEditorPage from './pages/WorkflowEditorPage'
|
||||
import './app.css'
|
||||
|
||||
function Nav() {
|
||||
@@ -194,6 +195,7 @@ function AppShell() {
|
||||
<Route path="/admin/prompts" element={<AdminPromptsPage/>}/>
|
||||
<Route path="/admin/goal-types" element={<AdminGoalTypesPage/>}/>
|
||||
<Route path="/admin/focus-areas" element={<AdminFocusAreasPage/>}/>
|
||||
<Route path="/workflow-editor/:id" element={<WorkflowEditorPage/>}/>
|
||||
<Route path="/subscription" element={<SubscriptionPage/>}/>
|
||||
</Routes>
|
||||
</main>
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import ReactFlow, { Background, Controls, MiniMap } from 'reactflow'
|
||||
import 'reactflow/dist/style.css'
|
||||
|
||||
/**
|
||||
* WorkflowCanvas - React Flow Wrapper Component
|
||||
*
|
||||
* Kapselt React Flow Setup (Background, Controls, MiniMap).
|
||||
* Separation of Concerns: Canvas-Logik getrennt von Editor-Orchestrierung.
|
||||
*
|
||||
* Props:
|
||||
* - nodes: Array of React Flow nodes
|
||||
* - edges: Array of React Flow edges
|
||||
* - nodeTypes: Object mapping node type to component
|
||||
* - onNodesChange: Handler for node changes (drag, delete, etc.)
|
||||
* - onEdgesChange: Handler for edge changes
|
||||
* - onConnect: Handler for new edge connections
|
||||
* - onNodeClick: Handler for node selection
|
||||
*/
|
||||
export function WorkflowCanvas({
|
||||
nodes,
|
||||
edges,
|
||||
nodeTypes,
|
||||
onNodesChange,
|
||||
onEdgesChange,
|
||||
onConnect,
|
||||
onNodeClick
|
||||
}) {
|
||||
return (
|
||||
<div style={{ width: '100%', height: '100%' }}>
|
||||
<ReactFlow
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onConnect={onConnect}
|
||||
onNodeClick={onNodeClick}
|
||||
nodeTypes={nodeTypes}
|
||||
fitView
|
||||
className="workflow-canvas"
|
||||
minZoom={0.2}
|
||||
maxZoom={2}
|
||||
defaultEdgeOptions={{
|
||||
animated: false,
|
||||
style: { strokeWidth: 2 }
|
||||
}}
|
||||
>
|
||||
<Background
|
||||
variant="dots"
|
||||
gap={16}
|
||||
size={1}
|
||||
color="var(--border)"
|
||||
/>
|
||||
<Controls
|
||||
showZoom={true}
|
||||
showFitView={true}
|
||||
showInteractive={true}
|
||||
/>
|
||||
<MiniMap
|
||||
nodeStrokeWidth={3}
|
||||
zoomable
|
||||
pannable
|
||||
style={{
|
||||
backgroundColor: 'var(--surface)',
|
||||
border: '1px solid var(--border)'
|
||||
}}
|
||||
/>
|
||||
</ReactFlow>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Handle, Position } from 'reactflow'
|
||||
|
||||
/**
|
||||
* AnalysisNode - KI-Prompt Knoten
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label
|
||||
* - data.prompt_id: ID des referenzierten Basis-Prompts
|
||||
* - data.prompt_name: Name des Prompts (optional, für Display)
|
||||
* - data.questions: Array von Question Augmentations
|
||||
* - selected: Boolean
|
||||
*/
|
||||
export function AnalysisNode({ data, selected }) {
|
||||
const hasQuestions = data.questions?.length > 0
|
||||
const promptName = data.prompt_name || (data.prompt_id ? `Prompt #${data.prompt_id}` : 'Kein Prompt')
|
||||
const questionCount = data.questions?.length || 0
|
||||
|
||||
return (
|
||||
<div className={`workflow-node analysis-node ${selected ? 'selected' : ''}`}>
|
||||
<div className="node-header">
|
||||
<div className="node-icon">🤖</div>
|
||||
<div className="node-label">{data.label || 'Analyse'}</div>
|
||||
</div>
|
||||
|
||||
<div className="node-body">
|
||||
<div className="prompt-name" title={promptName}>
|
||||
{promptName}
|
||||
</div>
|
||||
|
||||
{hasQuestions && (
|
||||
<div className="questions-indicator">
|
||||
📋 {questionCount} {questionCount === 1 ? 'Frage' : 'Fragen'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="in"
|
||||
style={{ background: 'var(--accent)' }}
|
||||
/>
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="out"
|
||||
style={{ background: 'var(--accent)' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Handle, Position } from 'reactflow'
|
||||
|
||||
/**
|
||||
* EndNode - Workflow Austritt
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label (default: "Ende")
|
||||
* - selected: Boolean (Node ist ausgewählt)
|
||||
*/
|
||||
export function EndNode({ data, selected }) {
|
||||
return (
|
||||
<div className={`workflow-node end-node ${selected ? 'selected' : ''}`}>
|
||||
<div className="node-icon">🏁</div>
|
||||
<div className="node-label">{data.label || 'Ende'}</div>
|
||||
|
||||
{/* Nur Target Handle (kein Source, da Endpunkt) */}
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="in"
|
||||
style={{ background: 'var(--danger)' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Handle, Position } from 'reactflow'
|
||||
|
||||
/**
|
||||
* JoinNode - Pfad-Konsolidierung
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label
|
||||
* - data.join_strategy: 'wait_all' | 'wait_any' | 'best_effort'
|
||||
* - data.skip_handling: 'ignore_skipped' | 'use_placeholder' | 'require_minimum'
|
||||
* - selected: Boolean
|
||||
*/
|
||||
export function JoinNode({ data, selected }) {
|
||||
const strategy = data.join_strategy || 'wait_all'
|
||||
const skipHandling = data.skip_handling || 'ignore_skipped'
|
||||
|
||||
// Strategy Display Names
|
||||
const strategyLabels = {
|
||||
'wait_all': 'Alle warten',
|
||||
'wait_any': 'Beliebig',
|
||||
'best_effort': 'Best Effort'
|
||||
}
|
||||
|
||||
const skipLabels = {
|
||||
'ignore_skipped': 'Ignorieren',
|
||||
'use_placeholder': 'Platzhalter',
|
||||
'require_minimum': 'Minimum'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`workflow-node join-node ${selected ? 'selected' : ''}`}>
|
||||
<div className="node-header">
|
||||
<div className="node-icon">🔀</div>
|
||||
<div className="node-label">{data.label || 'Join'}</div>
|
||||
</div>
|
||||
|
||||
<div className="node-body">
|
||||
<div className="strategy">
|
||||
<strong>Strategie:</strong> {strategyLabels[strategy] || strategy}
|
||||
</div>
|
||||
<div className="skip-handling">
|
||||
<strong>Skip:</strong> {skipLabels[skipHandling] || skipHandling}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mehrere Target Handles für eingehende Pfade */}
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_1"
|
||||
style={{ left: '25%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_2"
|
||||
style={{ left: '50%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_3"
|
||||
style={{ left: '75%', background: '#17A2B8' }}
|
||||
/>
|
||||
|
||||
{/* Ein Source Handle für konsolidierten Ausgang */}
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="out"
|
||||
style={{ background: '#17A2B8' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Handle, Position } from 'reactflow'
|
||||
|
||||
/**
|
||||
* LogicNode - Bedingungs-Knoten (If-Then-Else)
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label
|
||||
* - data.condition: Logic Expression Object
|
||||
* - selected: Boolean
|
||||
*/
|
||||
export function LogicNode({ data, selected }) {
|
||||
const hasCondition = !!data.condition && !!data.condition.operator
|
||||
|
||||
// Condition Summary (vereinfacht für Display)
|
||||
const getConditionSummary = () => {
|
||||
if (!hasCondition) return 'Keine Bedingung'
|
||||
|
||||
const op = data.condition.operator?.toUpperCase()
|
||||
const operandCount = data.condition.operands?.length || 0
|
||||
|
||||
if (op === 'AND' || op === 'OR' || op === 'NOT') {
|
||||
return `${op} (${operandCount} Bedingungen)`
|
||||
}
|
||||
|
||||
// Simple condition (ref, operator, value)
|
||||
if (data.condition.ref) {
|
||||
return `${data.condition.ref} ${data.condition.operator} ...`
|
||||
}
|
||||
|
||||
return 'Bedingung definiert'
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`workflow-node logic-node ${selected ? 'selected' : ''}`}>
|
||||
<div className="node-header">
|
||||
<div className="node-icon">⚡</div>
|
||||
<div className="node-label">{data.label || 'Logik'}</div>
|
||||
</div>
|
||||
|
||||
<div className="node-body">
|
||||
<div className={`condition-summary ${hasCondition ? 'has-condition' : 'no-condition'}`}>
|
||||
{getConditionSummary()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="in"
|
||||
style={{ background: '#FFC107' }}
|
||||
/>
|
||||
|
||||
{/* Zwei Source Handles für True/False Pfade */}
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="true"
|
||||
style={{ left: '33%', background: '#4CAF50' }}
|
||||
/>
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="false"
|
||||
style={{ left: '66%', background: '#F44336' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Handle, Position } from 'reactflow'
|
||||
|
||||
/**
|
||||
* StartNode - Workflow Einstiegspunkt
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label (default: "Start")
|
||||
* - selected: Boolean (Node ist ausgewählt)
|
||||
*/
|
||||
export function StartNode({ data, selected }) {
|
||||
return (
|
||||
<div className={`workflow-node start-node ${selected ? 'selected' : ''}`}>
|
||||
<div className="node-icon">🚀</div>
|
||||
<div className="node-label">{data.label || 'Start'}</div>
|
||||
|
||||
{/* Nur Source Handle (kein Target, da Einstiegspunkt) */}
|
||||
<Handle
|
||||
type="source"
|
||||
position={Position.Bottom}
|
||||
id="out"
|
||||
style={{ background: 'var(--accent)' }}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* FallbackConfig - Fallback-Strategie Konfiguration
|
||||
*
|
||||
* Props:
|
||||
* - node: React Flow Node object
|
||||
* - edges: Array of React Flow edges
|
||||
* - onChange: (nodeId, updates) => void
|
||||
*/
|
||||
export function FallbackConfig({ node, edges, onChange }) {
|
||||
const fallbackStrategy = node.data.fallback_strategy || 'conservative_skip'
|
||||
const fallbackEdge = node.data.fallback_edge || null
|
||||
|
||||
// Outgoing Edges von diesem Node
|
||||
const outgoingEdges = edges.filter(e => e.source === node.id)
|
||||
|
||||
const handleStrategyChange = (e) => {
|
||||
const strategy = e.target.value
|
||||
onChange(node.id, { fallback_strategy: strategy })
|
||||
|
||||
// Reset fallback_edge wenn strategy geändert wird
|
||||
if (strategy === 'conservative_skip' || strategy === 'document_only') {
|
||||
onChange(node.id, { fallback_edge: null })
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdgeChange = (e) => {
|
||||
onChange(node.id, { fallback_edge: e.target.value || null })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="config-section">
|
||||
<h3>Fallback-Strategie</h3>
|
||||
|
||||
<label>Strategie bei unklaren Signalen</label>
|
||||
<select value={fallbackStrategy} onChange={handleStrategyChange}>
|
||||
<option value="conservative_skip">Konservativ überspringen</option>
|
||||
<option value="default_path">Standardpfad ausführen</option>
|
||||
<option value="uncertainty_path">Unsicherheits-Pfad</option>
|
||||
<option value="document_only">Nur dokumentieren</option>
|
||||
</select>
|
||||
|
||||
<div className="help-text">
|
||||
{fallbackStrategy === 'conservative_skip' && 'Bei Unklarheit: Pfad nicht routen.'}
|
||||
{fallbackStrategy === 'default_path' && 'Bei Unklarheit: Definierter Standardpfad wird ausgeführt.'}
|
||||
{fallbackStrategy === 'uncertainty_path' && 'Bei Unklarheit: Expliziter Klärungspfad.'}
|
||||
{fallbackStrategy === 'document_only' && 'Unklarheit dokumentieren, aber kein Routing.'}
|
||||
</div>
|
||||
|
||||
{(fallbackStrategy === 'default_path' || fallbackStrategy === 'uncertainty_path') && (
|
||||
<>
|
||||
<label style={{ marginTop: '16px' }}>Ziel-Edge</label>
|
||||
<select value={fallbackEdge || ''} onChange={handleEdgeChange}>
|
||||
<option value="">-- Kante wählen --</option>
|
||||
{outgoingEdges.map(e => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{e.data?.label || `Edge → ${e.target}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{outgoingEdges.length === 0 && (
|
||||
<div className="help-text" style={{ color: 'var(--danger)' }}>
|
||||
⚠️ Keine ausgehenden Kanten gefunden. Bitte verbinden Sie diesen Node zuerst.
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* JoinConfig - Konfiguration für Join Nodes
|
||||
*
|
||||
* Props:
|
||||
* - node: React Flow Node object (type='join')
|
||||
* - onChange: (nodeId, updates) => void
|
||||
*/
|
||||
export function JoinConfig({ node, onChange }) {
|
||||
const joinStrategy = node.data.join_strategy || 'wait_all'
|
||||
const skipHandling = node.data.skip_handling || 'ignore_skipped'
|
||||
const minPaths = node.data.min_paths || 2
|
||||
|
||||
const handleStrategyChange = (e) => {
|
||||
onChange(node.id, { join_strategy: e.target.value })
|
||||
}
|
||||
|
||||
const handleSkipChange = (e) => {
|
||||
onChange(node.id, { skip_handling: e.target.value })
|
||||
}
|
||||
|
||||
const handleMinPathsChange = (e) => {
|
||||
const value = parseInt(e.target.value) || 2
|
||||
onChange(node.id, { min_paths: value })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="config-section">
|
||||
<h3>Join-Konfiguration</h3>
|
||||
|
||||
<label>Join-Strategie</label>
|
||||
<select value={joinStrategy} onChange={handleStrategyChange}>
|
||||
<option value="wait_all">Alle Pfade warten (wait_all)</option>
|
||||
<option value="wait_any">Mindestens ein Pfad (wait_any)</option>
|
||||
<option value="best_effort">Verfügbare nutzen (best_effort)</option>
|
||||
</select>
|
||||
|
||||
<div className="help-text">
|
||||
{joinStrategy === 'wait_all' && 'Wartet auf alle eingehenden Pfade. Fehler wenn einer fehlt.'}
|
||||
{joinStrategy === 'wait_any' && 'Wartet auf mindestens einen Pfad. Erste verfügbare Ausführung.'}
|
||||
{joinStrategy === 'best_effort' && 'Fehlertoleranz: Nutzt verfügbare Pfade, auch wenn nicht alle da sind.'}
|
||||
</div>
|
||||
|
||||
<label style={{ marginTop: '16px' }}>Skip-Handling</label>
|
||||
<select value={skipHandling} onChange={handleSkipChange}>
|
||||
<option value="ignore_skipped">Übersprungene ignorieren</option>
|
||||
<option value="use_placeholder">Platzhalter verwenden</option>
|
||||
<option value="require_minimum">Mindestanzahl erforderlich</option>
|
||||
</select>
|
||||
|
||||
{skipHandling === 'require_minimum' && (
|
||||
<>
|
||||
<label style={{ marginTop: '12px' }}>Mindestanzahl Pfade</label>
|
||||
<input
|
||||
type="number"
|
||||
min="1"
|
||||
value={minPaths}
|
||||
onChange={handleMinPathsChange}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="help-text" style={{ marginTop: '8px', fontSize: '11px', color: 'var(--text3)' }}>
|
||||
💡 Phase 4: Path Consolidation
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import { useState, useEffect, useMemo } from 'react'
|
||||
|
||||
/**
|
||||
* LogicExpressionEditor - Visueller Baukasten für Logik-Bedingungen
|
||||
*
|
||||
* KEIN JSON-Editor! Visuelles Drag & Drop Interface.
|
||||
*
|
||||
* Props:
|
||||
* - node: React Flow Node object (type='logic')
|
||||
* - nodes: Array of all nodes (for signal reference lookup)
|
||||
* - edges: Array of all edges (for topological sort)
|
||||
* - onChange: (nodeId, updates) => void
|
||||
*/
|
||||
export function LogicExpressionEditor({ node, nodes, edges, onChange }) {
|
||||
const [expression, setExpression] = useState(node.data.condition || {
|
||||
operator: 'and',
|
||||
operands: []
|
||||
})
|
||||
|
||||
// Verfügbare Signale aus vorangegangenen Nodes
|
||||
const availableSignals = useMemo(() => {
|
||||
return getAvailableSignals(node.id, nodes, edges)
|
||||
}, [node.id, nodes, edges])
|
||||
|
||||
// Sync to parent when expression changes
|
||||
useEffect(() => {
|
||||
onChange(node.id, { condition: expression })
|
||||
}, [expression])
|
||||
|
||||
const handleOperatorChange = (e) => {
|
||||
setExpression({ ...expression, operator: e.target.value })
|
||||
}
|
||||
|
||||
const handleAddCondition = () => {
|
||||
setExpression({
|
||||
...expression,
|
||||
operands: [...(expression.operands || []), {
|
||||
ref: '',
|
||||
operator: 'eq',
|
||||
value: ''
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
const handleAddGroup = () => {
|
||||
setExpression({
|
||||
...expression,
|
||||
operands: [...(expression.operands || []), {
|
||||
operator: 'and',
|
||||
operands: []
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
const handleOperandChange = (index, updates) => {
|
||||
const updated = [...(expression.operands || [])]
|
||||
updated[index] = { ...updated[index], ...updates }
|
||||
setExpression({ ...expression, operands: updated })
|
||||
}
|
||||
|
||||
const handleRemoveOperand = (index) => {
|
||||
setExpression({
|
||||
...expression,
|
||||
operands: (expression.operands || []).filter((_, i) => i !== index)
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="config-section">
|
||||
<h3>Logik-Bedingung</h3>
|
||||
|
||||
{availableSignals.length === 0 && (
|
||||
<div className="help-text" style={{ color: 'var(--danger)', marginBottom: '12px' }}>
|
||||
⚠️ Keine Signale verfügbar. Fügen Sie zuerst einen Analysis-Node VOR diesem Node hinzu.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="logic-root">
|
||||
<label>Verknüpfung (Root-Operator)</label>
|
||||
<select value={expression.operator || 'and'} onChange={handleOperatorChange}>
|
||||
<option value="and">UND (alle müssen zutreffen)</option>
|
||||
<option value="or">ODER (mind. eine muss zutreffen)</option>
|
||||
<option value="not">NICHT (umkehren)</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="logic-operands">
|
||||
{(expression.operands || []).map((operand, idx) => (
|
||||
<ConditionBlock
|
||||
key={idx}
|
||||
operand={operand}
|
||||
availableSignals={availableSignals}
|
||||
onChange={(updates) => handleOperandChange(idx, updates)}
|
||||
onRemove={() => handleRemoveOperand(idx)}
|
||||
/>
|
||||
))}
|
||||
|
||||
{(!expression.operands || expression.operands.length === 0) && (
|
||||
<div className="help-text" style={{ marginBottom: '12px' }}>
|
||||
Keine Bedingungen definiert. Fügen Sie Bedingungen oder Gruppen hinzu.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="logic-actions">
|
||||
<button className="btn-secondary" onClick={handleAddCondition}>
|
||||
+ Bedingung
|
||||
</button>
|
||||
<button className="btn-secondary" onClick={handleAddGroup}>
|
||||
+ Gruppe (AND/OR)
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="help-text" style={{ marginTop: '12px', fontSize: '11px', color: 'var(--text3)' }}>
|
||||
💡 Signale: {availableSignals.length} verfügbar
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ConditionBlock - Einzelne Bedingung oder Gruppe (rekursiv)
|
||||
*/
|
||||
function ConditionBlock({ operand, availableSignals, onChange, onRemove }) {
|
||||
// Verschachtelte Gruppe? (AND/OR/NOT)
|
||||
const isGroup = operand.operator === 'and' || operand.operator === 'or' || operand.operator === 'not'
|
||||
|
||||
if (isGroup) {
|
||||
return (
|
||||
<div className="condition-group">
|
||||
<div className="group-header">
|
||||
<select
|
||||
value={operand.operator}
|
||||
onChange={(e) => onChange({ operator: e.target.value })}
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<option value="and">UND</option>
|
||||
<option value="or">ODER</option>
|
||||
<option value="not">NICHT</option>
|
||||
</select>
|
||||
<button className="btn-icon" onClick={onRemove}>🗑️</button>
|
||||
</div>
|
||||
|
||||
{/* Rekursiv: Nested operands */}
|
||||
<div style={{ paddingLeft: '12px', borderLeft: '3px solid var(--accent)' }}>
|
||||
{(operand.operands || []).map((subOp, idx) => (
|
||||
<ConditionBlock
|
||||
key={idx}
|
||||
operand={subOp}
|
||||
availableSignals={availableSignals}
|
||||
onChange={(updates) => {
|
||||
const updated = [...(operand.operands || [])]
|
||||
updated[idx] = { ...updated[idx], ...updates }
|
||||
onChange({ operands: updated })
|
||||
}}
|
||||
onRemove={() => {
|
||||
onChange({ operands: (operand.operands || []).filter((_, i) => i !== idx) })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={() => {
|
||||
onChange({
|
||||
operands: [...(operand.operands || []), { ref: '', operator: 'eq', value: '' }]
|
||||
})
|
||||
}}
|
||||
style={{ marginTop: '8px', fontSize: '12px' }}
|
||||
>
|
||||
+ Bedingung
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Einfache Bedingung
|
||||
const selectedSignal = availableSignals.find(s => s.ref === operand.ref)
|
||||
|
||||
return (
|
||||
<div className="condition-simple">
|
||||
{/* Signal-Referenz (Dropdown) */}
|
||||
<select
|
||||
value={operand.ref || ''}
|
||||
onChange={(e) => onChange({ ref: e.target.value })}
|
||||
className="signal-select"
|
||||
style={{ flex: 2 }}
|
||||
>
|
||||
<option value="">-- Signal wählen --</option>
|
||||
{availableSignals.map(sig => (
|
||||
<option key={sig.ref} value={sig.ref}>
|
||||
{sig.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{/* Operator */}
|
||||
<select
|
||||
value={operand.operator || 'eq'}
|
||||
onChange={(e) => onChange({ operator: e.target.value })}
|
||||
className="operator-select"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<option value="eq">==</option>
|
||||
<option value="neq">!=</option>
|
||||
<option value="in">IN</option>
|
||||
<option value="not_in">NOT IN</option>
|
||||
<option value="gt">></option>
|
||||
<option value="lt"><</option>
|
||||
<option value="gte">>=</option>
|
||||
<option value="lte"><=</option>
|
||||
<option value="contains">CONTAINS</option>
|
||||
</select>
|
||||
|
||||
{/* Wert (abhängig von Operator) */}
|
||||
{(operand.operator === 'in' || operand.operator === 'not_in') ? (
|
||||
<MultiSelect
|
||||
options={selectedSignal?.spectrum || []}
|
||||
value={operand.value || []}
|
||||
onChange={(val) => onChange({ value: val })}
|
||||
placeholder="Werte wählen"
|
||||
/>
|
||||
) : (
|
||||
<input
|
||||
type="text"
|
||||
value={operand.value || ''}
|
||||
onChange={(e) => onChange({ value: e.target.value })}
|
||||
placeholder="Wert"
|
||||
className="value-input"
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
)}
|
||||
|
||||
<button className="btn-icon" onClick={onRemove}>🗑️</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* MultiSelect - Multi-Auswahl für IN/NOT_IN Operatoren
|
||||
*/
|
||||
function MultiSelect({ options, value, onChange, placeholder }) {
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const selected = Array.isArray(value) ? value : []
|
||||
|
||||
const handleToggle = (option) => {
|
||||
if (selected.includes(option)) {
|
||||
onChange(selected.filter(v => v !== option))
|
||||
} else {
|
||||
onChange([...selected, option])
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="multi-select" style={{ flex: 1, position: 'relative' }}>
|
||||
<div
|
||||
className="multi-select-display"
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
style={{
|
||||
padding: '6px',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '4px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '12px',
|
||||
background: 'var(--bg)'
|
||||
}}
|
||||
>
|
||||
{selected.length > 0 ? selected.join(', ') : placeholder}
|
||||
</div>
|
||||
|
||||
{isOpen && (
|
||||
<div
|
||||
className="multi-select-dropdown"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '100%',
|
||||
left: 0,
|
||||
right: 0,
|
||||
background: 'var(--surface)',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '4px',
|
||||
marginTop: '4px',
|
||||
maxHeight: '200px',
|
||||
overflowY: 'auto',
|
||||
zIndex: 1000
|
||||
}}
|
||||
>
|
||||
{options.map((option, i) => (
|
||||
<div
|
||||
key={i}
|
||||
onClick={() => handleToggle(option)}
|
||||
style={{
|
||||
padding: '8px',
|
||||
cursor: 'pointer',
|
||||
fontSize: '12px',
|
||||
background: selected.includes(option) ? 'var(--accent)' : 'transparent',
|
||||
color: selected.includes(option) ? 'white' : 'var(--text1)'
|
||||
}}
|
||||
>
|
||||
{selected.includes(option) && '✓ '}
|
||||
{option}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{options.length === 0 && (
|
||||
<div style={{ padding: '8px', fontSize: '12px', color: 'var(--text3)' }}>
|
||||
Keine Optionen verfügbar
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper: Verfügbare Signale aus vorangegangenen Nodes extrahieren
|
||||
*/
|
||||
function getAvailableSignals(nodeId, nodes, edges) {
|
||||
// Topologische Sortierung: Alle Nodes VOR diesem Node
|
||||
const predecessors = new Set()
|
||||
|
||||
function collectPredecessors(currentId) {
|
||||
const incoming = edges.filter(e => e.target === currentId)
|
||||
for (const edge of incoming) {
|
||||
if (!predecessors.has(edge.source)) {
|
||||
predecessors.add(edge.source)
|
||||
collectPredecessors(edge.source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collectPredecessors(nodeId)
|
||||
|
||||
// Signale extrahieren (nur von ANALYSIS Nodes)
|
||||
const signals = []
|
||||
for (const predId of predecessors) {
|
||||
const predNode = nodes.find(n => n.id === predId)
|
||||
if (predNode && predNode.type === 'analysis') {
|
||||
const questions = predNode.data.questions || []
|
||||
for (const q of questions) {
|
||||
signals.push({
|
||||
ref: `${predId}.${q.id}`,
|
||||
label: `${predNode.data.label} → ${q.question || q.id}`,
|
||||
spectrum: q.answer_spectrum || []
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return signals
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
|
||||
/**
|
||||
* QuestionAugmentationPanel - Fragenergänzungs-Konfiguration
|
||||
*
|
||||
* Props:
|
||||
* - node: React Flow Node object (type='analysis')
|
||||
* - onChange: (nodeId, updates) => void
|
||||
*/
|
||||
export function QuestionAugmentationPanel({ node, onChange }) {
|
||||
const [questions, setQuestions] = useState(node.data.questions || [])
|
||||
|
||||
// Sync to parent when questions change
|
||||
useEffect(() => {
|
||||
onChange(node.id, { questions })
|
||||
}, [questions])
|
||||
|
||||
const handleAddQuestion = () => {
|
||||
const newQuestion = {
|
||||
id: `q${Date.now()}`,
|
||||
type: 'relevanz',
|
||||
question: '',
|
||||
answer_spectrum: []
|
||||
}
|
||||
setQuestions([...questions, newQuestion])
|
||||
}
|
||||
|
||||
const handleRemoveQuestion = (index) => {
|
||||
setQuestions(questions.filter((_, i) => i !== index))
|
||||
}
|
||||
|
||||
const handleQuestionChange = (index, field, value) => {
|
||||
const updated = [...questions]
|
||||
updated[index] = { ...updated[index], [field]: value }
|
||||
setQuestions(updated)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="config-section">
|
||||
<h3>Fragenergänzung</h3>
|
||||
|
||||
{questions.length === 0 && (
|
||||
<div className="help-text" style={{ marginBottom: '12px' }}>
|
||||
Keine Fragen definiert. Fügen Sie Fragen hinzu, um Signale für Logik-Knoten zu erzeugen.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{questions.map((q, idx) => (
|
||||
<QuestionEditor
|
||||
key={q.id}
|
||||
question={q}
|
||||
index={idx}
|
||||
onChange={(field, value) => handleQuestionChange(idx, field, value)}
|
||||
onRemove={() => handleRemoveQuestion(idx)}
|
||||
/>
|
||||
))}
|
||||
|
||||
<button className="btn-secondary btn-full" onClick={handleAddQuestion}>
|
||||
+ Frage hinzufügen
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* QuestionEditor - Einzelne Frage editieren
|
||||
*/
|
||||
function QuestionEditor({ question, index, onChange, onRemove }) {
|
||||
const [spectrumInput, setSpectrumInput] = useState('')
|
||||
|
||||
const handleAddAnswer = () => {
|
||||
if (!spectrumInput.trim()) return
|
||||
|
||||
const newSpectrum = [...(question.answer_spectrum || []), spectrumInput.trim()]
|
||||
onChange('answer_spectrum', newSpectrum)
|
||||
setSpectrumInput('')
|
||||
}
|
||||
|
||||
const handleRemoveAnswer = (answer) => {
|
||||
const newSpectrum = question.answer_spectrum.filter(a => a !== answer)
|
||||
onChange('answer_spectrum', newSpectrum)
|
||||
}
|
||||
|
||||
const handleKeyPress = (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault()
|
||||
handleAddAnswer()
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="question-editor">
|
||||
<div className="question-header">
|
||||
<span>Frage {index + 1}</span>
|
||||
<button className="btn-icon" onClick={onRemove} title="Frage löschen">
|
||||
🗑️
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<label>Frage-ID</label>
|
||||
<input
|
||||
type="text"
|
||||
value={question.id || ''}
|
||||
onChange={(e) => onChange('id', e.target.value)}
|
||||
placeholder="z.B. relevanz"
|
||||
/>
|
||||
|
||||
<label>Fragetyp</label>
|
||||
<select
|
||||
value={question.type || 'relevanz'}
|
||||
onChange={(e) => onChange('type', e.target.value)}
|
||||
>
|
||||
<option value="relevanz">Relevanz</option>
|
||||
<option value="prioritaet">Priorität</option>
|
||||
<option value="selektion">Selektion</option>
|
||||
<option value="ausschluss">Ausschluss</option>
|
||||
<option value="eskalation">Eskalation</option>
|
||||
<option value="unsicherheit">Unsicherheit</option>
|
||||
</select>
|
||||
|
||||
<label>Fragetext</label>
|
||||
<textarea
|
||||
value={question.question || ''}
|
||||
onChange={(e) => onChange('question', e.target.value)}
|
||||
placeholder="z.B. Ist diese Analyse relevant für den Nutzer?"
|
||||
rows={3}
|
||||
/>
|
||||
|
||||
<label>Antwortmöglichkeiten (mind. 2)</label>
|
||||
<div className="tag-input-container">
|
||||
<div className="tags">
|
||||
{(question.answer_spectrum || []).map((answer, i) => (
|
||||
<span key={i} className="tag">
|
||||
{answer}
|
||||
<button
|
||||
onClick={() => handleRemoveAnswer(answer)}
|
||||
className="tag-remove"
|
||||
title="Entfernen"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div style={{ display: 'flex', gap: '8px', marginTop: '8px' }}>
|
||||
<input
|
||||
type="text"
|
||||
value={spectrumInput}
|
||||
onChange={(e) => setSpectrumInput(e.target.value)}
|
||||
onKeyPress={handleKeyPress}
|
||||
placeholder="z.B. ja, nein, unklar"
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
<button className="btn-secondary" onClick={handleAddAnswer}>
|
||||
+
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{question.answer_spectrum && question.answer_spectrum.length < 2 && (
|
||||
<div className="help-text" style={{ color: 'var(--danger)' }}>
|
||||
⚠️ Mindestens 2 Antworten erforderlich
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Zusätzliches CSS für Tags (inline styles)
|
||||
const tagStyles = `
|
||||
.tag-input-container {
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 4px 8px;
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tag-remove {
|
||||
background: none;
|
||||
border: none;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
padding: 0;
|
||||
margin-left: 2px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.tag-remove:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
`
|
||||
|
||||
// Inject styles (nur einmal)
|
||||
if (typeof document !== 'undefined' && !document.getElementById('question-panel-styles')) {
|
||||
const styleEl = document.createElement('style')
|
||||
styleEl.id = 'question-panel-styles'
|
||||
styleEl.textContent = tagStyles
|
||||
document.head.appendChild(styleEl)
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
import { useState, useCallback, useEffect } from 'react'
|
||||
import { useNavigate, useParams } from 'react-router-dom'
|
||||
import { useNodesState, useEdgesState, addEdge } from 'reactflow'
|
||||
import { api } from '../utils/api'
|
||||
import { validateWorkflowGraph } from '../utils/workflowValidation'
|
||||
import { serializeToWorkflowGraph, deserializeFromWorkflowGraph } from '../utils/workflowSerializer'
|
||||
import { WorkflowCanvas } from '../components/workflow/WorkflowCanvas'
|
||||
import { StartNode } from '../components/workflow/nodes/StartNode'
|
||||
import { EndNode } from '../components/workflow/nodes/EndNode'
|
||||
import { AnalysisNode } from '../components/workflow/nodes/AnalysisNode'
|
||||
import { LogicNode } from '../components/workflow/nodes/LogicNode'
|
||||
import { JoinNode } from '../components/workflow/nodes/JoinNode'
|
||||
import { QuestionAugmentationPanel } from '../components/workflow/panels/QuestionAugmentationPanel'
|
||||
import { LogicExpressionEditor } from '../components/workflow/panels/LogicExpressionEditor'
|
||||
import { FallbackConfig } from '../components/workflow/panels/FallbackConfig'
|
||||
import { JoinConfig } from '../components/workflow/panels/JoinConfig'
|
||||
import '../styles/workflowEditor.css'
|
||||
|
||||
// Node-Type Mapping
|
||||
const nodeTypes = {
|
||||
start: StartNode,
|
||||
end: EndNode,
|
||||
analysis: AnalysisNode,
|
||||
logic: LogicNode,
|
||||
join: JoinNode
|
||||
}
|
||||
|
||||
let nodeIdCounter = 1
|
||||
|
||||
export default function WorkflowEditorPage() {
|
||||
const navigate = useNavigate()
|
||||
const { id } = useParams() // prompt_id wenn vorhanden
|
||||
|
||||
// State
|
||||
const [nodes, setNodes, onNodesChange] = useNodesState([])
|
||||
const [edges, setEdges, onEdgesChange] = useEdgesState([])
|
||||
const [selectedNode, setSelectedNode] = useState(null)
|
||||
const [currentPrompt, setCurrentPrompt] = useState(null)
|
||||
const [workflowName, setWorkflowName] = useState('Neuer Workflow')
|
||||
const [workflowDescription, setWorkflowDescription] = useState('')
|
||||
const [validationErrors, setValidationErrors] = useState([])
|
||||
const [validationWarnings, setValidationWarnings] = useState([])
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState(null)
|
||||
|
||||
// Load workflow wenn ID vorhanden
|
||||
useEffect(() => {
|
||||
if (id && id !== 'new') {
|
||||
loadWorkflow(parseInt(id))
|
||||
}
|
||||
}, [id])
|
||||
|
||||
// Auto-Validation
|
||||
useEffect(() => {
|
||||
const { errors, warnings } = validateWorkflowGraph(nodes, edges)
|
||||
setValidationErrors(errors)
|
||||
setValidationWarnings(warnings)
|
||||
}, [nodes, edges])
|
||||
|
||||
// ── Handlers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const onConnect = useCallback(
|
||||
(params) => setEdges((eds) => addEdge(params, eds)),
|
||||
[setEdges]
|
||||
)
|
||||
|
||||
const onNodeClick = useCallback((event, node) => {
|
||||
setSelectedNode(node)
|
||||
}, [])
|
||||
|
||||
const handleAddNode = (nodeType) => {
|
||||
const newNode = {
|
||||
id: `node_${nodeIdCounter++}`,
|
||||
type: nodeType,
|
||||
position: { x: 250, y: 100 + nodes.length * 100 },
|
||||
data: {
|
||||
label: `${nodeType.charAt(0).toUpperCase() + nodeType.slice(1)} ${nodeIdCounter - 1}`
|
||||
}
|
||||
}
|
||||
|
||||
setNodes((nds) => [...nds, newNode])
|
||||
}
|
||||
|
||||
const handleNodeUpdate = (nodeId, updates) => {
|
||||
setNodes((nds) =>
|
||||
nds.map((n) => (n.id === nodeId ? { ...n, data: { ...n.data, ...updates } } : n))
|
||||
)
|
||||
}
|
||||
|
||||
const handleDeleteNode = () => {
|
||||
if (!selectedNode) return
|
||||
|
||||
setNodes((nds) => nds.filter((n) => n.id !== selectedNode.id))
|
||||
setEdges((eds) => eds.filter((e) => e.source !== selectedNode.id && e.target !== selectedNode.id))
|
||||
setSelectedNode(null)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
// Validierung
|
||||
const { errors, isValid } = validateWorkflowGraph(nodes, edges)
|
||||
if (!isValid) {
|
||||
setError(`Validierung fehlgeschlagen: ${errors.length} Fehler gefunden`)
|
||||
return
|
||||
}
|
||||
|
||||
// Serialisieren
|
||||
const graph_data = serializeToWorkflowGraph(nodes, edges, {
|
||||
created_at: currentPrompt?.created_at,
|
||||
version: '1.0'
|
||||
})
|
||||
|
||||
if (currentPrompt) {
|
||||
// Update existing
|
||||
await api.updateUnifiedPrompt(currentPrompt.id, {
|
||||
type: 'workflow',
|
||||
name: workflowName,
|
||||
description: workflowDescription,
|
||||
graph_data
|
||||
})
|
||||
alert('Workflow gespeichert!')
|
||||
} else {
|
||||
// Create new
|
||||
const result = await api.createUnifiedPrompt({
|
||||
type: 'workflow',
|
||||
name: workflowName,
|
||||
description: workflowDescription,
|
||||
graph_data
|
||||
})
|
||||
setCurrentPrompt({ id: result.id, name: workflowName })
|
||||
navigate(`/workflow-editor/${result.id}`)
|
||||
alert('Workflow erstellt!')
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadWorkflow = async (promptId) => {
|
||||
try {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
const prompt = await api.getPrompt(promptId)
|
||||
|
||||
if (prompt.type !== 'workflow') {
|
||||
throw new Error('Nicht ein Workflow')
|
||||
}
|
||||
|
||||
// Deserialisieren
|
||||
const { nodes: loadedNodes, edges: loadedEdges } = deserializeFromWorkflowGraph(prompt.graph_data)
|
||||
|
||||
setNodes(loadedNodes)
|
||||
setEdges(loadedEdges)
|
||||
setCurrentPrompt(prompt)
|
||||
setWorkflowName(prompt.name)
|
||||
setWorkflowDescription(prompt.description || '')
|
||||
|
||||
// nodeIdCounter aktualisieren
|
||||
const maxId = Math.max(
|
||||
...loadedNodes.map((n) => parseInt(n.id.replace('node_', '')) || 0),
|
||||
0
|
||||
)
|
||||
nodeIdCounter = maxId + 1
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleValidate = () => {
|
||||
const { errors, warnings } = validateWorkflowGraph(nodes, edges)
|
||||
setValidationErrors(errors)
|
||||
setValidationWarnings(warnings)
|
||||
|
||||
if (errors.length === 0) {
|
||||
alert(`✅ Workflow ist valide!\n\n${warnings.length} Warnungen`)
|
||||
} else {
|
||||
alert(`❌ Validierung fehlgeschlagen!\n\n${errors.length} Fehler, ${warnings.length} Warnungen`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleNew = () => {
|
||||
if (confirm('Neuen Workflow erstellen? Ungespeicherte Änderungen gehen verloren.')) {
|
||||
setNodes([])
|
||||
setEdges([])
|
||||
setCurrentPrompt(null)
|
||||
setWorkflowName('Neuer Workflow')
|
||||
setWorkflowDescription('')
|
||||
setSelectedNode(null)
|
||||
navigate('/workflow-editor/new')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!currentPrompt) return
|
||||
|
||||
if (!confirm(`Workflow "${workflowName}" wirklich löschen?`)) return
|
||||
|
||||
try {
|
||||
setLoading(true)
|
||||
await api.deletePrompt(currentPrompt.id)
|
||||
alert('Workflow gelöscht')
|
||||
navigate('/admin/prompts')
|
||||
} catch (e) {
|
||||
setError(e.message)
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Render ────────────────────────────────────────────────────────────────
|
||||
|
||||
return (
|
||||
<div className="workflow-editor">
|
||||
{/* Toolbar */}
|
||||
<div className="workflow-toolbar">
|
||||
<button className="btn-secondary" onClick={() => navigate('/admin/prompts')}>
|
||||
← Zurück
|
||||
</button>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={workflowName}
|
||||
onChange={(e) => setWorkflowName(e.target.value)}
|
||||
placeholder="Workflow-Name"
|
||||
style={{ flex: 1, padding: '8px', borderRadius: '4px', border: '1px solid var(--border)' }}
|
||||
/>
|
||||
|
||||
<button className="btn-secondary" onClick={handleNew}>
|
||||
Neu
|
||||
</button>
|
||||
<button className="btn-secondary" onClick={handleValidate}>
|
||||
Validieren
|
||||
</button>
|
||||
<button className="btn-primary" onClick={handleSave} disabled={loading}>
|
||||
{loading ? 'Speichern...' : 'Speichern'}
|
||||
</button>
|
||||
{currentPrompt && (
|
||||
<button className="btn-secondary" onClick={handleDelete} disabled={loading}>
|
||||
Löschen
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div style={{ padding: '12px', background: 'var(--danger)', color: 'white' }}>
|
||||
❌ {error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="workflow-content">
|
||||
{/* Sidebar */}
|
||||
<div className="workflow-sidebar">
|
||||
<div className="sidebar-section">
|
||||
<h3>Workflow-Knoten</h3>
|
||||
<div className="node-palette">
|
||||
<button className="node-palette-button" onClick={() => handleAddNode('start')}>
|
||||
<span className="icon">🚀</span> Start
|
||||
</button>
|
||||
<button className="node-palette-button" onClick={() => handleAddNode('analysis')}>
|
||||
<span className="icon">🤖</span> Analyse
|
||||
</button>
|
||||
<button className="node-palette-button" onClick={() => handleAddNode('logic')}>
|
||||
<span className="icon">⚡</span> Logik
|
||||
</button>
|
||||
<button className="node-palette-button" onClick={() => handleAddNode('join')}>
|
||||
<span className="icon">🔀</span> Join
|
||||
</button>
|
||||
<button className="node-palette-button" onClick={() => handleAddNode('end')}>
|
||||
<span className="icon">🏁</span> Ende
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{selectedNode && (
|
||||
<div className="sidebar-section">
|
||||
<h3>Aktionen</h3>
|
||||
<button className="btn-secondary btn-full" onClick={handleDeleteNode}>
|
||||
🗑️ Node löschen
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="sidebar-section">
|
||||
<h3>Info</h3>
|
||||
<div style={{ fontSize: '12px', color: 'var(--text3)' }}>
|
||||
<div>Nodes: {nodes.length}</div>
|
||||
<div>Edges: {edges.length}</div>
|
||||
<div>Errors: {validationErrors.length}</div>
|
||||
<div>Warnings: {validationWarnings.length}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Canvas */}
|
||||
<div className="workflow-canvas-container">
|
||||
<WorkflowCanvas
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onConnect={onConnect}
|
||||
onNodeClick={onNodeClick}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Config Panel */}
|
||||
{selectedNode && (
|
||||
<div className="workflow-config-panel">
|
||||
<h2 style={{ margin: '0 0 16px 0' }}>{selectedNode.data.label}</h2>
|
||||
|
||||
{/* Basis-Konfiguration */}
|
||||
<div className="config-section">
|
||||
<label>Label</label>
|
||||
<input
|
||||
type="text"
|
||||
value={selectedNode.data.label || ''}
|
||||
onChange={(e) => handleNodeUpdate(selectedNode.id, { label: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Type-spezifische Konfiguration */}
|
||||
{selectedNode.type === 'analysis' && (
|
||||
<>
|
||||
<QuestionAugmentationPanel node={selectedNode} onChange={handleNodeUpdate} />
|
||||
<FallbackConfig node={selectedNode} edges={edges} onChange={handleNodeUpdate} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{selectedNode.type === 'logic' && (
|
||||
<>
|
||||
<LogicExpressionEditor
|
||||
node={selectedNode}
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
onChange={handleNodeUpdate}
|
||||
/>
|
||||
<FallbackConfig node={selectedNode} edges={edges} onChange={handleNodeUpdate} />
|
||||
</>
|
||||
)}
|
||||
|
||||
{selectedNode.type === 'join' && (
|
||||
<JoinConfig node={selectedNode} onChange={handleNodeUpdate} />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Validation Panel */}
|
||||
{(validationErrors.length > 0 || validationWarnings.length > 0) && (
|
||||
<div className="validation-panel">
|
||||
{validationErrors.map((err, i) => (
|
||||
<div key={i} className="validation-error" onClick={() => {
|
||||
if (err.nodeId) {
|
||||
const node = nodes.find(n => n.id === err.nodeId)
|
||||
if (node) setSelectedNode(node)
|
||||
}
|
||||
}}>
|
||||
❌ {err.message}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{validationWarnings.map((warn, i) => (
|
||||
<div key={i} className="validation-warning" onClick={() => {
|
||||
if (warn.nodeId) {
|
||||
const node = nodes.find(n => n.id === warn.nodeId)
|
||||
if (node) setSelectedNode(node)
|
||||
}
|
||||
}}>
|
||||
⚠️ {warn.message}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{validationErrors.length === 0 && validationWarnings.length > 0 && (
|
||||
<div className="validation-success">
|
||||
✅ Workflow ist valide ({validationWarnings.length} Warnungen)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,471 @@
|
||||
/* Workflow Editor Styles (Phase 5) */
|
||||
|
||||
/* ── Editor Layout ────────────────────────────────────────────────────────── */
|
||||
|
||||
.workflow-editor {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 60px);
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.workflow-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 12px 16px;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.workflow-content {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* ── Sidebar (Node Palette) ─────────────────────────────────────────────── */
|
||||
|
||||
.workflow-sidebar {
|
||||
width: 250px;
|
||||
background: var(--surface);
|
||||
border-right: 1px solid var(--border);
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.sidebar-section {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.sidebar-section h3 {
|
||||
margin: 0 0 12px 0;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--text2);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.node-palette {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.node-palette-button {
|
||||
padding: 12px;
|
||||
background: var(--surface2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-size: 14px;
|
||||
color: var(--text1);
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.node-palette-button:hover {
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
border-color: var(--accent);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.node-palette-button .icon {
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
/* ── Canvas ──────────────────────────────────────────────────────────────── */
|
||||
|
||||
.workflow-canvas-container {
|
||||
flex: 1;
|
||||
position: relative;
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
/* React Flow Overrides */
|
||||
.react-flow {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
.react-flow__node {
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
.react-flow__node.selected {
|
||||
box-shadow: 0 0 0 3px rgba(29, 158, 117, 0.3);
|
||||
}
|
||||
|
||||
.react-flow__edge-path {
|
||||
stroke: var(--text3);
|
||||
stroke-width: 2;
|
||||
}
|
||||
|
||||
.react-flow__edge.selected .react-flow__edge-path {
|
||||
stroke: var(--accent);
|
||||
stroke-width: 3;
|
||||
}
|
||||
|
||||
.react-flow__handle {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border: 2px solid white;
|
||||
}
|
||||
|
||||
.react-flow__handle-connecting {
|
||||
background: var(--accent) !important;
|
||||
}
|
||||
|
||||
.react-flow__handle-valid {
|
||||
background: #4CAF50 !important;
|
||||
}
|
||||
|
||||
/* ── Custom Nodes ────────────────────────────────────────────────────────── */
|
||||
|
||||
.workflow-node {
|
||||
min-width: 180px;
|
||||
background: var(--surface);
|
||||
border: 2px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||
font-family: inherit;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
|
||||
.workflow-node:hover {
|
||||
box-shadow: 0 4px 8px rgba(0,0,0,0.15);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.workflow-node.selected {
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 3px rgba(29, 158, 117, 0.2);
|
||||
}
|
||||
|
||||
.node-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.node-icon {
|
||||
font-size: 20px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.node-label {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
color: var(--text1);
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.node-body {
|
||||
font-size: 12px;
|
||||
color: var(--text2);
|
||||
}
|
||||
|
||||
/* Start Node */
|
||||
.workflow-node.start-node {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
border-color: #667eea;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.workflow-node.start-node .node-label,
|
||||
.workflow-node.start-node .node-body {
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* End Node */
|
||||
.workflow-node.end-node {
|
||||
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
|
||||
color: white;
|
||||
border-color: #f093fb;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.workflow-node.end-node .node-label,
|
||||
.workflow-node.end-node .node-body {
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Analysis Node */
|
||||
.workflow-node.analysis-node {
|
||||
background: var(--surface2);
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.workflow-node.analysis-node .prompt-name {
|
||||
font-weight: 500;
|
||||
color: var(--text1);
|
||||
margin-bottom: 4px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.workflow-node.analysis-node .questions-indicator {
|
||||
font-size: 11px;
|
||||
color: var(--accent);
|
||||
padding: 4px 8px;
|
||||
background: rgba(29, 158, 117, 0.1);
|
||||
border-radius: 4px;
|
||||
display: inline-block;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* Logic Node */
|
||||
.workflow-node.logic-node {
|
||||
background: #FFF3CD;
|
||||
border-color: #FFC107;
|
||||
}
|
||||
|
||||
.workflow-node.logic-node .condition-summary {
|
||||
padding: 6px 8px;
|
||||
background: rgba(255, 193, 7, 0.2);
|
||||
border-radius: 4px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.workflow-node.logic-node .condition-summary.has-condition {
|
||||
color: #856404;
|
||||
}
|
||||
|
||||
.workflow-node.logic-node .condition-summary.no-condition {
|
||||
color: #6c757d;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Join Node */
|
||||
.workflow-node.join-node {
|
||||
background: #D1ECF1;
|
||||
border-color: #17A2B8;
|
||||
}
|
||||
|
||||
.workflow-node.join-node .node-body {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.workflow-node.join-node .strategy,
|
||||
.workflow-node.join-node .skip-handling {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.workflow-node.join-node strong {
|
||||
color: #0c5460;
|
||||
}
|
||||
|
||||
/* ── Config Panel ────────────────────────────────────────────────────────── */
|
||||
|
||||
.workflow-config-panel {
|
||||
width: 400px;
|
||||
background: var(--surface);
|
||||
border-left: 1px solid var(--border);
|
||||
padding: 16px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.config-section {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.config-section h3 {
|
||||
margin: 0 0 12px 0;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
color: var(--text1);
|
||||
}
|
||||
|
||||
.config-section label {
|
||||
display: block;
|
||||
margin-bottom: 4px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text2);
|
||||
}
|
||||
|
||||
.config-section input,
|
||||
.config-section select,
|
||||
.config-section textarea {
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
margin-bottom: 8px;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
background: var(--bg);
|
||||
color: var(--text1);
|
||||
}
|
||||
|
||||
.config-section textarea {
|
||||
resize: vertical;
|
||||
min-height: 60px;
|
||||
}
|
||||
|
||||
/* ── Question Editor ─────────────────────────────────────────────────────── */
|
||||
|
||||
.question-editor {
|
||||
background: var(--surface2);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
margin-bottom: 12px;
|
||||
}
|
||||
|
||||
.question-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.question-header span {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
color: var(--text1);
|
||||
}
|
||||
|
||||
.btn-icon {
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
font-size: 18px;
|
||||
padding: 4px;
|
||||
opacity: 0.7;
|
||||
transition: opacity 0.2s;
|
||||
}
|
||||
|
||||
.btn-icon:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* ── Logic Expression Editor ─────────────────────────────────────────────── */
|
||||
|
||||
.logic-root {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.logic-operands {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.condition-block {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
padding: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.condition-simple {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.condition-simple select,
|
||||
.condition-simple input {
|
||||
flex: 1;
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.condition-group {
|
||||
border-left: 3px solid var(--accent);
|
||||
padding-left: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.group-header {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.logic-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
/* ── Validation Panel ────────────────────────────────────────────────────── */
|
||||
|
||||
.validation-panel {
|
||||
position: fixed;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: var(--surface);
|
||||
border-top: 1px solid var(--border);
|
||||
padding: 12px 16px;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
z-index: 1000;
|
||||
}
|
||||
|
||||
.validation-error {
|
||||
color: var(--danger);
|
||||
margin-bottom: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.validation-error:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.validation-warning {
|
||||
color: #FFC107;
|
||||
margin-bottom: 4px;
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.validation-warning:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.validation-success {
|
||||
color: #4CAF50;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ── Responsive ──────────────────────────────────────────────────────────── */
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.workflow-sidebar {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.workflow-config-panel {
|
||||
width: 350px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.workflow-content {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.workflow-sidebar,
|
||||
.workflow-config-panel {
|
||||
width: 100%;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
@@ -286,6 +286,7 @@ export const api = {
|
||||
|
||||
// AI Prompts Management (Issue #28)
|
||||
listAdminPrompts: () => req('/prompts'),
|
||||
getPrompt: (id) => req(`/prompts/${id}`),
|
||||
createPrompt: (d) => req('/prompts', json(d)),
|
||||
updatePrompt: (id,d) => req(`/prompts/${id}`, jput(d)),
|
||||
deletePrompt: (id) => req(`/prompts/${id}`, {method:'DELETE'}),
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
/**
|
||||
* Workflow Serialization Utilities
|
||||
*
|
||||
* Konvertiert zwischen React Flow (Canvas) und Backend-Format (JSONB).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Serialisiert React Flow Graph zu Backend-kompatiblem Format
|
||||
*
|
||||
* @param {Array} nodes - React Flow nodes
|
||||
* @param {Array} edges - React Flow edges
|
||||
* @param {Object} metadata - Zusätzliche Metadaten
|
||||
* @returns {Object} JSONB-kompatibles Objekt für ai_prompts.graph_data
|
||||
*/
|
||||
export function serializeToWorkflowGraph(nodes, edges, metadata = {}) {
|
||||
const workflowNodes = nodes.map(node => ({
|
||||
id: node.id,
|
||||
type: node.type,
|
||||
label: node.data.label || node.type,
|
||||
position: { x: node.position.x, y: node.position.y },
|
||||
|
||||
// Type-spezifische Felder
|
||||
...(node.type === 'analysis' && {
|
||||
prompt_id: node.data.prompt_id || null,
|
||||
questions: node.data.questions || [],
|
||||
fallback_strategy: node.data.fallback_strategy || 'conservative_skip'
|
||||
}),
|
||||
|
||||
...(node.type === 'logic' && {
|
||||
condition: node.data.condition || null,
|
||||
fallback_strategy: node.data.fallback_strategy || 'conservative_skip'
|
||||
}),
|
||||
|
||||
...(node.type === 'join' && {
|
||||
join_strategy: node.data.join_strategy || 'wait_all',
|
||||
skip_handling: node.data.skip_handling || 'ignore_skipped',
|
||||
min_paths: node.data.min_paths || 2
|
||||
})
|
||||
}))
|
||||
|
||||
const workflowEdges = edges.map(edge => ({
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
label: edge.data?.label || null,
|
||||
sourceHandle: edge.sourceHandle || null,
|
||||
targetHandle: edge.targetHandle || null
|
||||
}))
|
||||
|
||||
return {
|
||||
nodes: workflowNodes,
|
||||
edges: workflowEdges,
|
||||
metadata: {
|
||||
created_at: metadata.created_at || new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
version: metadata.version || '1.0'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialisiert Backend-Format zu React Flow Graph
|
||||
*
|
||||
* @param {Object} jsonbData - ai_prompts.graph_data (JSONB)
|
||||
* @returns {Object} { nodes, edges, metadata }
|
||||
*/
|
||||
export function deserializeFromWorkflowGraph(jsonbData) {
|
||||
if (!jsonbData || !jsonbData.nodes || !jsonbData.edges) {
|
||||
throw new Error('Invalid workflow graph data')
|
||||
}
|
||||
|
||||
const reactFlowNodes = jsonbData.nodes.map(node => ({
|
||||
id: node.id,
|
||||
type: node.type,
|
||||
position: { x: node.position.x, y: node.position.y },
|
||||
data: {
|
||||
label: node.label,
|
||||
|
||||
...(node.type === 'analysis' && {
|
||||
prompt_id: node.prompt_id,
|
||||
prompt_name: node.prompt_name || null, // Falls vom Backend mitgeliefert
|
||||
questions: node.questions || [],
|
||||
fallback_strategy: node.fallback_strategy || 'conservative_skip'
|
||||
}),
|
||||
|
||||
...(node.type === 'logic' && {
|
||||
condition: node.condition || null,
|
||||
fallback_strategy: node.fallback_strategy || 'conservative_skip'
|
||||
}),
|
||||
|
||||
...(node.type === 'join' && {
|
||||
join_strategy: node.join_strategy || 'wait_all',
|
||||
skip_handling: node.skip_handling || 'ignore_skipped',
|
||||
min_paths: node.min_paths || 2
|
||||
})
|
||||
}
|
||||
}))
|
||||
|
||||
const reactFlowEdges = jsonbData.edges.map(edge => ({
|
||||
id: edge.id,
|
||||
source: edge.source,
|
||||
target: edge.target,
|
||||
sourceHandle: edge.sourceHandle || null,
|
||||
targetHandle: edge.targetHandle || null,
|
||||
data: {
|
||||
label: edge.label || null
|
||||
},
|
||||
type: 'default',
|
||||
animated: false
|
||||
}))
|
||||
|
||||
return {
|
||||
nodes: reactFlowNodes,
|
||||
edges: reactFlowEdges,
|
||||
metadata: jsonbData.metadata || {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
/**
|
||||
* Workflow Validation Utilities
|
||||
*
|
||||
* Validiert Workflow-Graphen (Struktur + Logik).
|
||||
*/
|
||||
|
||||
export function validateWorkflowGraph(nodes, edges) {
|
||||
const errors = []
|
||||
const warnings = []
|
||||
|
||||
// 1. Strukturelle Validierung
|
||||
validateStructure(nodes, edges, errors, warnings)
|
||||
|
||||
// 2. Logische Validierung
|
||||
validateLogic(nodes, edges, errors, warnings)
|
||||
|
||||
return {
|
||||
errors,
|
||||
warnings,
|
||||
isValid: errors.length === 0
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Strukturelle Validierung (DAG, START/END, Zyklen)
|
||||
*/
|
||||
function validateStructure(nodes, edges, errors, warnings) {
|
||||
// START Node
|
||||
const startNodes = nodes.filter(n => n.type === 'start')
|
||||
if (startNodes.length === 0) {
|
||||
errors.push({
|
||||
type: 'structure',
|
||||
message: 'Kein START-Node vorhanden',
|
||||
severity: 'error'
|
||||
})
|
||||
} else if (startNodes.length > 1) {
|
||||
errors.push({
|
||||
type: 'structure',
|
||||
message: `${startNodes.length} START-Nodes gefunden (max. 1 erlaubt)`,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
// END Node
|
||||
const endNodes = nodes.filter(n => n.type === 'end')
|
||||
if (endNodes.length === 0) {
|
||||
errors.push({
|
||||
type: 'structure',
|
||||
message: 'Kein END-Node vorhanden',
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
// Zyklen-Erkennung
|
||||
if (detectCycles(nodes, edges)) {
|
||||
errors.push({
|
||||
type: 'structure',
|
||||
message: 'Workflow enthält Zyklen (nicht erlaubt)',
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
// Isolierte Nodes
|
||||
nodes.forEach(node => {
|
||||
if (node.type === 'start' || node.type === 'end') return
|
||||
|
||||
const hasIncoming = edges.some(e => e.target === node.id)
|
||||
const hasOutgoing = edges.some(e => e.source === node.id)
|
||||
|
||||
if (!hasIncoming || !hasOutgoing) {
|
||||
warnings.push({
|
||||
type: 'isolation',
|
||||
message: `Node "${node.data.label}" ist isoliert (keine/fehlende Verbindungen)`,
|
||||
nodeId: node.id,
|
||||
severity: 'warning'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Logische Validierung (Node-Konfiguration)
|
||||
*/
|
||||
function validateLogic(nodes, edges, errors, warnings) {
|
||||
nodes.forEach(node => {
|
||||
// Analysis Nodes
|
||||
if (node.type === 'analysis') {
|
||||
const questions = node.data.questions || []
|
||||
|
||||
// Prompt ausgewählt?
|
||||
if (!node.data.prompt_id) {
|
||||
errors.push({
|
||||
type: 'config',
|
||||
message: `Analysis-Node "${node.data.label}" hat keinen Prompt`,
|
||||
nodeId: node.id,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
// Fragen validieren
|
||||
questions.forEach((q, idx) => {
|
||||
if (!q.question?.trim()) {
|
||||
errors.push({
|
||||
type: 'config',
|
||||
message: `Frage ${idx + 1} in "${node.data.label}" hat keinen Text`,
|
||||
nodeId: node.id,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
if (!q.answer_spectrum || q.answer_spectrum.length < 2) {
|
||||
errors.push({
|
||||
type: 'config',
|
||||
message: `Frage ${idx + 1} in "${node.data.label}" braucht mind. 2 Antworten`,
|
||||
nodeId: node.id,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Logic Nodes
|
||||
if (node.type === 'logic') {
|
||||
const condition = node.data.condition
|
||||
|
||||
if (!condition || !condition.operator) {
|
||||
errors.push({
|
||||
type: 'config',
|
||||
message: `Logic-Node "${node.data.label}" hat keine Bedingung`,
|
||||
nodeId: node.id,
|
||||
severity: 'error'
|
||||
})
|
||||
} else {
|
||||
// Bedingung vollständig?
|
||||
const incomplete = findIncompleteConditions(condition)
|
||||
if (incomplete.length > 0) {
|
||||
errors.push({
|
||||
type: 'config',
|
||||
message: `Logic-Node "${node.data.label}" hat ${incomplete.length} unvollständige Bedingung(en)`,
|
||||
nodeId: node.id,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Mind. 2 Outgoing Edges (true/false Pfade)
|
||||
const outgoing = edges.filter(e => e.source === node.id)
|
||||
if (outgoing.length < 2) {
|
||||
warnings.push({
|
||||
type: 'config',
|
||||
message: `Logic-Node "${node.data.label}" hat nur ${outgoing.length} Ausgang (sollte mind. 2 haben)`,
|
||||
nodeId: node.id,
|
||||
severity: 'warning'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Join Nodes
|
||||
if (node.type === 'join') {
|
||||
const incoming = edges.filter(e => e.target === node.id)
|
||||
|
||||
if (incoming.length < 2) {
|
||||
warnings.push({
|
||||
type: 'config',
|
||||
message: `Join-Node "${node.data.label}" hat nur ${incoming.length} eingehende Kante (sollte mind. 2 haben)`,
|
||||
nodeId: node.id,
|
||||
severity: 'warning'
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Zyklen-Erkennung (DFS-basiert)
|
||||
*/
|
||||
function detectCycles(nodes, edges) {
|
||||
const visited = new Set()
|
||||
const recStack = new Set()
|
||||
|
||||
function dfs(nodeId) {
|
||||
visited.add(nodeId)
|
||||
recStack.add(nodeId)
|
||||
|
||||
const outgoing = edges.filter(e => e.source === nodeId)
|
||||
for (const edge of outgoing) {
|
||||
if (!visited.has(edge.target)) {
|
||||
if (dfs(edge.target)) return true
|
||||
} else if (recStack.has(edge.target)) {
|
||||
return true // Cycle detected
|
||||
}
|
||||
}
|
||||
|
||||
recStack.delete(nodeId)
|
||||
return false
|
||||
}
|
||||
|
||||
for (const node of nodes) {
|
||||
if (!visited.has(node.id)) {
|
||||
if (dfs(node.id)) return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Unvollständige Bedingungen finden (rekursiv)
|
||||
*/
|
||||
function findIncompleteConditions(condition) {
|
||||
const incomplete = []
|
||||
|
||||
// Verschachtelte Gruppe?
|
||||
if (condition.operands && Array.isArray(condition.operands)) {
|
||||
for (const op of condition.operands) {
|
||||
incomplete.push(...findIncompleteConditions(op))
|
||||
}
|
||||
} else {
|
||||
// Einfache Bedingung: ref, operator, value müssen gesetzt sein
|
||||
if (!condition.ref || !condition.operator || condition.value === undefined || condition.value === '') {
|
||||
incomplete.push(condition)
|
||||
}
|
||||
}
|
||||
|
||||
return incomplete
|
||||
}
|
||||
Reference in new issue
Block a user