Compare commits
26
Commits
12893cba78
...
V1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5f745fc3e | ||
|
|
549c31431e | ||
|
|
3fa01dd686 | ||
|
|
c9357d4c0e | ||
|
|
f3a61091c7 | ||
|
|
10d24bbef7 | ||
|
|
ff8104a533 | ||
|
|
3b7f89a214 | ||
|
|
ba773e677b | ||
|
|
2443b5ac3a | ||
|
|
4c9e0e3c98 | ||
|
|
0ce98e8973 | ||
|
|
d803f39de3 | ||
|
|
300d96a9d8 | ||
|
|
28b6fb28d5 | ||
|
|
8b731313df | ||
|
|
3541c416f9 | ||
|
|
8d89b23db1 | ||
|
|
c0525cf2d2 | ||
|
|
88f0b5a0a4 | ||
|
|
aeb0ee6ad9 | ||
|
|
a4c8b4bd9a | ||
|
|
8f6d60681e | ||
|
|
65500c899b | ||
|
|
a1723db387 | ||
|
|
b453ce63c6 |
No files matched your search
@@ -12,6 +12,7 @@ Dieser Ordner ist der **primäre Orientierungspunkt** für Claude Code / Cursor-
|
||||
| 2 | **`rules/DOCUMENTATION.md`** – Ablage- und Dokumentationsregeln |
|
||||
| 3 | `rules/ARCHITECTURE.md`, `rules/CODING_RULES.md`, `rules/LESSONS_LEARNED.md` |
|
||||
| 4 | Issue-Landkarte: **`.claude/docs/GITEA_ISSUES_INDEX.md`** |
|
||||
| 5 | **Universal CSV Import** (Modul/Executor/Vorlagen): **`docs/technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md`** (unter `.claude/`) |
|
||||
|
||||
Themen mit UI/Nav/PWA: siehe `../docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md` (im **Projekt**-`docs/`, nicht hier).
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Gitea Issues – Landkarte (Auswertung)
|
||||
|
||||
**Quelle:** Gitea `Lars/mitai-jinkendo`, Stand **2026-04-08** (Abfrage `state=all`).
|
||||
**Quelle:** Gitea `Lars/mitai-jinkendo`, Stand **2026-04-09** (Abfrage `state=all`, ergänzt: #71).
|
||||
**URL:** http://192.168.2.144:3000/Lars/mitai-jinkendo/issues
|
||||
|
||||
Dieses Dokument ist ein **Orientierungs-Index** für Agenten und Entwickler. Verbindliches Tracking bleibt **in Gitea**; hier: Kategorien, Dubletten-Hinweise, grobe Prioritätseinschätzung.
|
||||
@@ -88,7 +88,6 @@ Dieses Dokument ist ein **Orientierungs-Index** für Agenten und Entwickler. Ver
|
||||
| # | Titel |
|
||||
|---|--------|
|
||||
| 15 | [FEAT-002] Quality-Filter für KI-Auswertungen & Charts integrieren |
|
||||
| 21 | [FEATURE] Universeller CSV-Parser mit lernbarem Feldmapping |
|
||||
| 36 | BUG-009: Trainingstyp-Erstellung führt zu Internal Server Error |
|
||||
|
||||
---
|
||||
|
||||
@@ -54,6 +54,7 @@ _Dieser Ordner `.claude/docs/` ist per `.gitignore`-Ausnahme **versioniert** (Sp
|
||||
| Platzhalter / Registry | `technical/PLACEHOLDER_REGISTRY_FRAMEWORK.md`, `technical/PLACEHOLDER_DEVELOPMENT_GUIDE.md` | `backend/placeholder_registrations/`, `backend/placeholder_resolver.py` |
|
||||
| Dashboard-Lab-Widgets | `technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md` | Widget-Katalog + Registrierung (siehe Guide) |
|
||||
| Training Profiler / Resolver | `technical/TRAINING_PROFILE_RESOLVER_LAYER1.md`, `functional/TRAINING_TYPE_PROFILES.md` | Resolver-Module wie im Guide genannt |
|
||||
| Universal CSV Import | `technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md` | `backend/csv_parser/`, `routers/csv_import.py`, `routers/admin_csv_templates.py` |
|
||||
| Mitgliedschaft / Features | `technical/MEMBERSHIP_SYSTEM.md`, `architecture/FEATURE_ENFORCEMENT.md` | `backend/auth.py`, Feature-Logging, Router mit Enforcement |
|
||||
|
||||
---
|
||||
@@ -111,6 +112,7 @@ _Dieser Ordner `.claude/docs/` ist per `.gitignore`-Ausnahme **versioniert** (Sp
|
||||
| `PROFILE_REFERENCE_VALUES.md` | Profil-Referenzwerte |
|
||||
| `TRAINING_PROFILE_RESOLVER_LAYER1.md` | Training-Resolver Schicht 1 |
|
||||
| `TRAINING_TYPE_PROFILES_TECHNICAL.md` | Trainingsprofile technisch |
|
||||
| `UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md` | Universal CSV: Registry, Executor, Vorlagen, Agent-Checkliste |
|
||||
| `V9D_PHASE2_VITALS_SLEEP.md` | v9d Vitalwerte/Schlaf (Release-Bezug) |
|
||||
|
||||
---
|
||||
@@ -174,4 +176,4 @@ Siehe [`audit/README.md`](./audit/README.md).
|
||||
|
||||
---
|
||||
|
||||
**Letzte Aktualisierung:** 8. April 2026 (Struktur-Index, Duplikatbereinigung, Abgleich-Hinweise)
|
||||
**Letzte Aktualisierung:** 9. April 2026 (Universal CSV Agent-Guide, Abgleich-Tabelle)
|
||||
@@ -0,0 +1,63 @@
|
||||
# Universal CSV Import – Agent-Leitfaden
|
||||
|
||||
**Stand:** 2026-04-09 · **Kontext:** Issue #21 (Universeller CSV-Parser), Prod-Migrationen u. a. 051–053.
|
||||
|
||||
Dieses Dokument ist **normativ für Agenten**, die ein neues Import-Zielmodul anlegen oder bestehende Import-Pfade (Executor, Vorlagen, DB) ändern.
|
||||
|
||||
---
|
||||
|
||||
## 1. Architektur (Kurz)
|
||||
|
||||
| Komponente | Pfad / Rolle |
|
||||
|------------|----------------|
|
||||
| Modul-Definitionen | `backend/csv_parser/module_registry.py` (`MODULE_DEFINITIONS`) |
|
||||
| Typ-/Einheiten-Konvertierung | `backend/csv_parser/type_converter.py`, `field_units.py` |
|
||||
| Zeilen-Aggregation (z. B. Ernährung pro Tag) | `backend/csv_parser/import_row_processing.py` |
|
||||
| Import-Ausführung | `backend/csv_parser/executor.py` |
|
||||
| Fehlertexte / Transaktions-Hinweise | `backend/csv_parser/import_errors.py` (`enrich_row_error`) |
|
||||
| Admin-Systemvorlagen | `backend/routers/admin_csv_templates.py` |
|
||||
| Nutzer-Import (Profil-Mappings) | `backend/routers/csv_import.py` |
|
||||
| Vorlagen-Validierung (strukturell + Sample) | `backend/csv_parser/template_validator.py` (`validate_csv_template`) |
|
||||
|
||||
**Single Source of Truth** für erlaubte Zielfelder, Typen und Duplikat-Keys ist **`module_registry.py`**. Keine parallele Feldliste in Routern duplizieren.
|
||||
|
||||
---
|
||||
|
||||
## 2. Checkliste: Neues Zielmodul
|
||||
|
||||
1. **`MODULE_DEFINITIONS`** um Eintrag erweitern: `table`, `fields` (Typen `date` / `datetime` / `float` / `int` / `string`), `duplicate_key`, `duplicate_strategy`, ggf. `derive_date_from_datetime_field`, `import_mode` (Spezialpfade wie Schlaf).
|
||||
2. **DB:** Migration nur nach Projektregel (`backend/migrations/NNN_*.sql`). Spaltenbreiten/Typen so wählen, dass importierte Werte (z. B. kJ→kcal, große Energiebeträge) **keinen NUMERIC-Overflow** verursachen.
|
||||
3. **`source` / CHECK-Constraints:** Wenn die Zieltabelle `source` hat, muss der Wert **`csv`** (oder der vereinbarte Import-Tag) in der DB erlaubt sein (Migration anpassen, nicht nur App-Code).
|
||||
4. **Executor:** Einfügen/Aktualisieren in `executor.py` nur über bestehende Muster (ein Cursor, **kein** verschachteltes `get_db()` im gleichen Request). Bei mehreren Zeilen pro Transaktion: bei **Zeilenfehlern** SAVEPOINT pro Zeile nutzen (siehe Activity-Pattern), damit die Transaktion nicht dauerhaft abgebrochen ist.
|
||||
5. **Trainingstyp / FK-Auflösung:** DB-Zugriffe für abhängige Entitäten (z. B. `get_training_type_for_activity_with_cursor`) **mit dem gleichen Cursor** wie der Import – keine zweite Connection aus dem Importpfad.
|
||||
6. **Vorlagen:** System-Templates in Migration/Seed pflegen (`csv_field_mappings`, `is_system=true`). `type_conversions` und `source_unit` dort setzen, wo Einheiten aus Exporten abweichen (z. B. Apple kJ).
|
||||
7. **Validierung:** Neue/angepasste Admin-Vorlagen müssen **`validate_csv_template`** passieren (Create/Update liefert bei Fehlern **422** mit `validation`). Tests für Randfälle ergänzen (`tests/test_template_validator.py` o. ä.).
|
||||
8. **API / Frontend:** Neue Admin-Endpunkte in `main.py` registrieren; Frontend **nur** über `api.js`. Bei strukturierten FastAPI-Fehlern (`detail` als Objekt/Liste) bestehende Hilfen (`formatFastApiDetail`) nutzen.
|
||||
|
||||
---
|
||||
|
||||
## 3. Checkliste: Bestehendes Modul ändern
|
||||
|
||||
- Schema-Änderung: Migration + ggf. **`module_registry`**-Felder anpassen.
|
||||
- Neue Spalte im Import: Executor-Mapping, optional `type_conversions` / Validator.
|
||||
- Änderung an Duplikatlogik: `duplicate_key` / `ON CONFLICT`-Pfad im Executor prüfen.
|
||||
- Datums-/Zeit-Parsing: **`type_converter`** – ISO-Daten `YYYY-MM-DD` konsistent (**`dayfirst=False`**), Zeiten `HH:MM` ohne Sekunden unterstützen wo nötig.
|
||||
|
||||
---
|
||||
|
||||
## 4. Bekannte Einschränkungen (Follow-up in Gitea)
|
||||
|
||||
- Admin **„Format prüfen“** kann `import_row_processing` derzeit weglassen; volle Parität mit dem gespeicherten Template erst beim Speichern / echten Import.
|
||||
- Nutzer-Mappings (Copy aus Systemvorlage) laufen nicht automatisch durch **`validate_csv_template`** – Tracking: **Gitea #71** (http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/71).
|
||||
|
||||
---
|
||||
|
||||
## 5. Verwandte Regeln
|
||||
|
||||
- `.claude/rules/ARCHITECTURE.md` – Router, DB, `source`-Tracking
|
||||
- `.claude/rules/CODING_RULES.md` – Kurzverweis Universal CSV
|
||||
- `.claude/rules/DOCUMENTATION.md` – Ablage technischer Specs
|
||||
|
||||
---
|
||||
|
||||
**Version:** 1.0
|
||||
@@ -0,0 +1,11 @@
|
||||
Folgende Ergebnisse des Tests:
|
||||
- Valididierung gibt immer noch keine Aufschlüsse was für Fehler und Warning es sind, Es zeigt immer nur noch die Anzahl der entsprechenden Fehler/Warnungen
|
||||
- Speichern als kurzes PopUp -- gut
|
||||
- In der Node selbst wird nun eine Fehlermeldung ausgegeben. Das ist gut. In größen Workflows aber schwierig den Fehler zu lokalisieren.
|
||||
- In der automatischen Zusammenfassung in der Endnode kommt als Überschrift, z.B. Node 10, anstatt den Node-Name auszugeben.
|
||||
- Alle Änderungen an Nodes scheinen automatisch in den Gesamtflow übernommen zu werden. Diese werden dann nach dem Speichern aktiv. Da muss man sehr vorsichtig sein, bei kurzen Änderungen und dem Ausprobieren.
|
||||
- Der Testlauf "Execute" sollte auf dem aktuellen Workflowstand ausgeführt werden, auch wenn dieser vom gespeicherten Abweicht. Ich würde natürlich vor dem Speichern den Workflow testen können. Prüfe und bewerte diesen Punkt, setze ihn aber noch nicht um.
|
||||
- Die Workflows werden aktuell nicht in Analyse und den verfügbaren KI-Asuwertungen angezeigt. ggf. weil wir sie aktuell noch keinem Bereich zuordnen können. Diesen könnten wir ggf. über die Start-Node im Workflow konfigurieren.
|
||||
- Das löschen von Knoten und Kanten funktioniert aktuell nur über Backspace nicht über entfernen
|
||||
- Wir sollten auch dafür sorgen, dass jeweils nur eine Start-Node, End-Node in einem Workflow existiert, Prüfe ob mehrere End-Nodes sinnvoll sind, da wir ja auch Logik-Pfade abbilden und ggf. auch eine route beschreiten, die ein anderes Ende hat. (Prüfe, ob das heute schon möglich wäre!)
|
||||
- Als zukünftige Ausbaustufe sollten wir überlegen, ob wir auch Trigger implementieren, z.B. um Kurzstatements zu generieren, wenn neue Daten hereinkommen und wir diese Bewertungen aktualisieren wollen
|
||||
@@ -216,8 +216,11 @@ updated_at TIMESTAMP DEFAULT NOW()
|
||||
Tabellen die Daten aus externen Quellen empfangen brauchen:
|
||||
```sql
|
||||
source VARCHAR(50) DEFAULT 'manual'
|
||||
-- Werte: 'manual' | 'apple_health' | 'garmin' | 'withings'
|
||||
-- Werte u. a.: 'manual' | 'apple_health' | 'garmin' | 'withings' | 'csv'
|
||||
```
|
||||
Importe über den **Universal CSV**-Pfad setzen `source = 'csv'`, sofern die Tabelle ein `source`-Feld hat; CHECK-Constraints und Migrationen müssen diesen Wert erlauben.
|
||||
|
||||
**Agent-Pflicht bei neuen Import-Zielen oder Executor-Änderungen:** `.claude/docs/technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md`
|
||||
|
||||
Manuelle Einträge (`source = 'manual'`) haben IMMER Vorrang bei Reimport:
|
||||
```sql
|
||||
|
||||
@@ -39,6 +39,13 @@ from slowapi import Limiter
|
||||
def sensitive(request: Request, ...):
|
||||
```
|
||||
|
||||
### 6. Universal CSV Import / Admin-Vorlagen
|
||||
Neues **Import-Zielmodul**, Änderungen an **`csv_parser`**, Executor, DB-`source`/`CHECK`, oder System-CSV-Vorlagen:
|
||||
|
||||
- Pflichtlektüre und Checkliste: **`.claude/docs/technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md`**
|
||||
- Keine zweite DB-Connection im Importpfad; Zeilenfehler ohne „aborted transaction“ (SAVEPOINT-Muster wo nötig)
|
||||
- Admin Create/Update von Systemvorlagen: Validierung über `validate_csv_template` nicht umgehen
|
||||
|
||||
## Frontend
|
||||
|
||||
### 1. api.js für alle API-Calls
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
> | Coding-Regeln | `.claude/rules/CODING_RULES.md` |
|
||||
> | Lessons Learned | `.claude/rules/LESSONS_LEARNED.md` |
|
||||
> | **Gitea-Landkarte (lokal gepflegt)** | **`.claude/docs/GITEA_ISSUES_INDEX.md`** |
|
||||
> | **Universal CSV Import** (neues Modul / Executor / Vorlagen) | **`.claude/docs/technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md`** |
|
||||
> | **GUI / IA / Admin / Nav / PWA-Leiste** | **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`** |
|
||||
> | **Dashboard-Lab-Widgets** (Katalog, Registrierung, `config`) | **`.claude/docs/technical/DASHBOARD_WIDGETS_AGENT_GUIDE.md`** |
|
||||
> | **Agent-Einstieg** | **`.claude/README.md`** |
|
||||
@@ -98,6 +99,12 @@ frontend/src/
|
||||
**Branch:** develop
|
||||
**Nächster Schritt:** Frontend Chart Integration → Testing → Prod Deploy v0.9i
|
||||
|
||||
### Updates (09.04.2026 - Universal CSV Import, Prod-Migration abgeschlossen)
|
||||
|
||||
- **Agent-Leitfaden:** `.claude/docs/technical/UNIVERSAL_CSV_IMPORT_AGENT_GUIDE.md` (Checkliste für neue Import-Module, Executor, Vorlagen, `source=csv`, SAVEPOINT-/Cursor-Regeln)
|
||||
- **Regeln:** Verweise in `.claude/rules/ARCHITECTURE.md` (§3.2 `source`), `.claude/rules/CODING_RULES.md` (§6)
|
||||
- **Follow-ups:** **Gitea #71** – Dry-Run inkl. `import_row_processing`, Nutzer-Mapping-Validierung, Fehler-Hints in der Import-UI ([Issue](http://192.168.2.144:3000/Lars/mitai-jinkendo/issues/71))
|
||||
|
||||
### GUI / Informationsarchitektur (Abnahme dieser Iteration, 2026-04-05)
|
||||
|
||||
Admin-Bereich (`AdminShell`, Hub-Routen), Hauptnavigation inkl. **Ziele** (`config/appNav.js`), Einstellungen nur aktives Profil + E-Mail, KI-Analyse Ergebnis in rechter Spalte, **PWA** Bottom-Nav inkl. iOS Safe Area. Zentrale Agent-Doku: **`docs/issues/GUI_IA_ADMIN_NAV_2026-04-05.md`**. Responsive-Epic **Gitea #30:** Phasenplan `docs/issues/PHASE_PLAN_RESPONSIVE_UI.md` — **P7 Kern erledigt**, **P8** (Regression/Abnahme) ausstehend; Issue bewusst **nicht** geschlossen.
|
||||
|
||||
+212
-133
@@ -31,6 +31,42 @@ OPENROUTER_MODEL = os.getenv("OPENROUTER_MODEL", "anthropic/claude-sonnet-4")
|
||||
|
||||
router = APIRouter(prefix="/api/prompts", tags=["prompts"])
|
||||
|
||||
# Metadaten-Schlüssel in workflow aggregate_results (nicht als „einziger“ Nutzer-Output)
|
||||
_WORKFLOW_AGG_META_KEYS = frozenset({
|
||||
"combined_analysis",
|
||||
"all_signals",
|
||||
"total_nodes",
|
||||
"executed_nodes",
|
||||
"failed_nodes",
|
||||
"skipped_nodes",
|
||||
})
|
||||
|
||||
|
||||
def _workflow_user_facing_content(agg: object) -> str:
|
||||
"""
|
||||
Nutzer-sichtbarer Text wie im Admin WorkflowResultViewer („Final Output“):
|
||||
primär aggregated_result['analysis_core'], nicht das gesamte JSON.
|
||||
"""
|
||||
if agg is None:
|
||||
return ""
|
||||
if isinstance(agg, str):
|
||||
return agg
|
||||
if not isinstance(agg, dict):
|
||||
return json.dumps(agg, ensure_ascii=False)
|
||||
core = agg.get("analysis_core")
|
||||
if isinstance(core, str) and core.strip():
|
||||
return core
|
||||
combined = agg.get("combined_analysis")
|
||||
if isinstance(combined, str) and combined.strip():
|
||||
return combined
|
||||
non_meta = [k for k in agg.keys() if k not in _WORKFLOW_AGG_META_KEYS]
|
||||
if len(non_meta) == 1:
|
||||
v = agg[non_meta[0]]
|
||||
if isinstance(v, str):
|
||||
return v
|
||||
return json.dumps(v, ensure_ascii=False)
|
||||
return json.dumps(agg, ensure_ascii=False)
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_prompts(session: dict=Depends(require_auth)):
|
||||
@@ -67,6 +103,156 @@ def list_placeholders_endpoint(session: dict=Depends(require_auth)):
|
||||
return get_placeholder_catalog(profile_id)
|
||||
|
||||
|
||||
@router.get("/export-all")
|
||||
def export_all_prompts(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Export all prompts as JSON array.
|
||||
Admin only. Used for backup and dev→prod sync.
|
||||
|
||||
IMPORTANT: Must be defined BEFORE /{prompt_id} route to avoid routing conflict.
|
||||
"""
|
||||
from datetime import datetime
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM ai_prompts ORDER BY sort_order, slug")
|
||||
prompts = [r2d(row) for row in cur.fetchall()]
|
||||
|
||||
# Convert to export format (clean up DB-specific fields)
|
||||
export_data = []
|
||||
for p in prompts:
|
||||
export_item = {
|
||||
'slug': p['slug'],
|
||||
'name': p['name'],
|
||||
'display_name': p.get('display_name'),
|
||||
'description': p.get('description'),
|
||||
'type': p.get('type', 'pipeline'),
|
||||
'category': p.get('category', 'ganzheitlich'),
|
||||
'template': p.get('template'),
|
||||
'stages': p.get('stages'),
|
||||
'output_format': p.get('output_format', 'text'),
|
||||
'output_schema': p.get('output_schema'),
|
||||
'question_augmentations': p.get('question_augmentations'),
|
||||
'graph_data': p.get('graph_data'),
|
||||
'active': p.get('active', True),
|
||||
'sort_order': p.get('sort_order', 0)
|
||||
}
|
||||
export_data.append(export_item)
|
||||
|
||||
return {
|
||||
'export_date': datetime.now().isoformat(),
|
||||
'count': len(export_data),
|
||||
'prompts': export_data
|
||||
}
|
||||
|
||||
|
||||
@router.post("/import")
|
||||
def import_prompts(
|
||||
data: dict,
|
||||
overwrite: bool = False,
|
||||
session: dict = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Import prompts from JSON export.
|
||||
|
||||
Args:
|
||||
data: Export data from /export-all endpoint
|
||||
overwrite: If true, update existing prompts. If false, skip duplicates.
|
||||
|
||||
Returns:
|
||||
Summary of import results (created, updated, skipped)
|
||||
|
||||
IMPORTANT: Must be defined BEFORE /{prompt_id} route to avoid routing conflict.
|
||||
"""
|
||||
if 'prompts' not in data:
|
||||
raise HTTPException(400, "Invalid import data: missing 'prompts' key")
|
||||
|
||||
prompts = data['prompts']
|
||||
created = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
errors = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
for p in prompts:
|
||||
slug = p.get('slug')
|
||||
if not slug:
|
||||
errors.append('Prompt without slug skipped')
|
||||
continue
|
||||
|
||||
# Check if exists
|
||||
cur.execute("SELECT id FROM ai_prompts WHERE slug=%s", (slug,))
|
||||
existing = cur.fetchone()
|
||||
|
||||
if existing and not overwrite:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Prepare JSON fields if present
|
||||
stages_json = None
|
||||
if p.get('stages'):
|
||||
stages_json = json.dumps(p['stages']) if isinstance(p['stages'], list) else p['stages']
|
||||
|
||||
output_schema_json = None
|
||||
if p.get('output_schema'):
|
||||
output_schema_json = json.dumps(p['output_schema']) if isinstance(p['output_schema'], dict) else p['output_schema']
|
||||
|
||||
question_aug_json = None
|
||||
if p.get('question_augmentations'):
|
||||
question_aug_json = json.dumps(p['question_augmentations']) if isinstance(p['question_augmentations'], (dict, list)) else p['question_augmentations']
|
||||
|
||||
graph_data_json = None
|
||||
if p.get('graph_data'):
|
||||
graph_data_json = json.dumps(p['graph_data']) if isinstance(p['graph_data'], dict) else p['graph_data']
|
||||
|
||||
if existing:
|
||||
# Update existing
|
||||
cur.execute("""
|
||||
UPDATE ai_prompts SET
|
||||
name=%s, display_name=%s, description=%s, type=%s,
|
||||
category=%s, template=%s, stages=%s, output_format=%s,
|
||||
output_schema=%s, question_augmentations=%s, graph_data=%s,
|
||||
active=%s, sort_order=%s,
|
||||
updated=CURRENT_TIMESTAMP
|
||||
WHERE slug=%s
|
||||
""", (
|
||||
p.get('name'), p.get('display_name'), p.get('description'),
|
||||
p.get('type', 'pipeline'), p.get('category', 'ganzheitlich'),
|
||||
p.get('template'), stages_json, p.get('output_format', 'text'),
|
||||
output_schema_json, question_aug_json, graph_data_json,
|
||||
p.get('active', True), p.get('sort_order', 0), slug
|
||||
))
|
||||
updated += 1
|
||||
else:
|
||||
# Create new
|
||||
cur.execute("""
|
||||
INSERT INTO ai_prompts (
|
||||
slug, name, display_name, description, type, category,
|
||||
template, stages, output_format, output_schema,
|
||||
question_augmentations, graph_data,
|
||||
active, sort_order, created, updated
|
||||
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
||||
""", (
|
||||
slug, p.get('name'), p.get('display_name'), p.get('description'),
|
||||
p.get('type', 'pipeline'), p.get('category', 'ganzheitlich'),
|
||||
p.get('template'), stages_json, p.get('output_format', 'text'),
|
||||
output_schema_json, question_aug_json, graph_data_json,
|
||||
p.get('active', True), p.get('sort_order', 0)
|
||||
))
|
||||
created += 1
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'created': created,
|
||||
'updated': updated,
|
||||
'skipped': skipped,
|
||||
'errors': errors if errors else None
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{prompt_id}")
|
||||
def get_prompt(prompt_id: str, session: dict=Depends(require_auth)):
|
||||
"""Get single AI prompt by ID (UUID)."""
|
||||
@@ -178,11 +364,31 @@ def duplicate_prompt(prompt_id: str, session: dict=Depends(require_admin)):
|
||||
|
||||
new_display_name = f"{original.get('display_name') or original['name']} (Kopie)"
|
||||
|
||||
# Prepare JSONB fields (convert dict/list to JSON string if needed)
|
||||
stages_json = json.dumps(original['stages']) if original.get('stages') else None
|
||||
output_schema_json = json.dumps(original['output_schema']) if original.get('output_schema') else None
|
||||
question_aug_json = json.dumps(original['question_augmentations']) if original.get('question_augmentations') else None
|
||||
graph_data_json = json.dumps(original['graph_data']) if original.get('graph_data') else None
|
||||
|
||||
cur.execute(
|
||||
"""INSERT INTO ai_prompts (id, name, slug, display_name, description, template, category, active, sort_order, created, updated)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)""",
|
||||
(new_id, new_name, new_slug, new_display_name, original['description'], original['template'],
|
||||
original.get('category', 'ganzheitlich'), original['active'], original['sort_order'])
|
||||
"""INSERT INTO ai_prompts (
|
||||
id, name, slug, display_name, description, template, category,
|
||||
type, stages, output_format, output_schema,
|
||||
question_augmentations, graph_data,
|
||||
active, sort_order, created, updated
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, %s,
|
||||
%s, %s, %s, %s,
|
||||
%s, %s,
|
||||
%s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
||||
)""",
|
||||
(new_id, new_name, new_slug, new_display_name,
|
||||
original.get('description'), original.get('template'),
|
||||
original.get('category', 'ganzheitlich'),
|
||||
original.get('type', 'pipeline'), stages_json,
|
||||
original.get('output_format', 'text'), output_schema_json,
|
||||
question_aug_json, graph_data_json,
|
||||
original.get('active', True), original.get('sort_order', 0))
|
||||
)
|
||||
|
||||
return {"id": new_id, "slug": new_slug, "name": new_name}
|
||||
@@ -1253,6 +1459,8 @@ async def execute_unified_prompt(
|
||||
content = list(final_output.values())[0]
|
||||
else:
|
||||
content = json.dumps(final_output, ensure_ascii=False)
|
||||
elif result['type'] == 'workflow':
|
||||
content = _workflow_user_facing_content(result.get('aggregated_result'))
|
||||
else:
|
||||
# For base prompts, use output directly
|
||||
content = result.get('output', '')
|
||||
@@ -1569,132 +1777,3 @@ def update_unified_prompt(prompt_id: str, p: UnifiedPromptUpdate, session: dict
|
||||
)
|
||||
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/export-all")
|
||||
def export_all_prompts(session: dict = Depends(require_admin)):
|
||||
"""
|
||||
Export all prompts as JSON array.
|
||||
Admin only. Used for backup and dev→prod sync.
|
||||
"""
|
||||
from datetime import datetime
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute("SELECT * FROM ai_prompts ORDER BY sort_order, slug")
|
||||
prompts = [r2d(row) for row in cur.fetchall()]
|
||||
|
||||
# Convert to export format (clean up DB-specific fields)
|
||||
export_data = []
|
||||
for p in prompts:
|
||||
export_item = {
|
||||
'slug': p['slug'],
|
||||
'name': p['name'],
|
||||
'display_name': p.get('display_name'),
|
||||
'description': p.get('description'),
|
||||
'type': p.get('type', 'pipeline'),
|
||||
'category': p.get('category', 'ganzheitlich'),
|
||||
'template': p.get('template'),
|
||||
'stages': p.get('stages'),
|
||||
'output_format': p.get('output_format', 'text'),
|
||||
'output_schema': p.get('output_schema'),
|
||||
'active': p.get('active', True),
|
||||
'sort_order': p.get('sort_order', 0)
|
||||
}
|
||||
export_data.append(export_item)
|
||||
|
||||
return {
|
||||
'export_date': datetime.now().isoformat(),
|
||||
'count': len(export_data),
|
||||
'prompts': export_data
|
||||
}
|
||||
|
||||
|
||||
@router.post("/import")
|
||||
def import_prompts(
|
||||
data: dict,
|
||||
overwrite: bool = False,
|
||||
session: dict = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Import prompts from JSON export.
|
||||
|
||||
Args:
|
||||
data: Export data from /export-all endpoint
|
||||
overwrite: If true, update existing prompts. If false, skip duplicates.
|
||||
|
||||
Returns:
|
||||
Summary of import results (created, updated, skipped)
|
||||
"""
|
||||
if 'prompts' not in data:
|
||||
raise HTTPException(400, "Invalid import data: missing 'prompts' key")
|
||||
|
||||
prompts = data['prompts']
|
||||
created = 0
|
||||
updated = 0
|
||||
skipped = 0
|
||||
errors = []
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
|
||||
for p in prompts:
|
||||
slug = p.get('slug')
|
||||
if not slug:
|
||||
errors.append('Prompt without slug skipped')
|
||||
continue
|
||||
|
||||
# Check if exists
|
||||
cur.execute("SELECT id FROM ai_prompts WHERE slug=%s", (slug,))
|
||||
existing = cur.fetchone()
|
||||
|
||||
if existing and not overwrite:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
# Prepare stages JSON if present
|
||||
stages_json = None
|
||||
if p.get('stages'):
|
||||
stages_json = json.dumps(p['stages']) if isinstance(p['stages'], list) else p['stages']
|
||||
|
||||
if existing:
|
||||
# Update existing
|
||||
cur.execute("""
|
||||
UPDATE ai_prompts SET
|
||||
name=%s, display_name=%s, description=%s, type=%s,
|
||||
category=%s, template=%s, stages=%s, output_format=%s,
|
||||
output_schema=%s, active=%s, sort_order=%s,
|
||||
updated=CURRENT_TIMESTAMP
|
||||
WHERE slug=%s
|
||||
""", (
|
||||
p.get('name'), p.get('display_name'), p.get('description'),
|
||||
p.get('type', 'pipeline'), p.get('category', 'ganzheitlich'),
|
||||
p.get('template'), stages_json, p.get('output_format', 'text'),
|
||||
p.get('output_schema'), p.get('active', True),
|
||||
p.get('sort_order', 0), slug
|
||||
))
|
||||
updated += 1
|
||||
else:
|
||||
# Create new
|
||||
cur.execute("""
|
||||
INSERT INTO ai_prompts (
|
||||
slug, name, display_name, description, type, category,
|
||||
template, stages, output_format, output_schema,
|
||||
active, sort_order, created, updated
|
||||
) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)
|
||||
""", (
|
||||
slug, p.get('name'), p.get('display_name'), p.get('description'),
|
||||
p.get('type', 'pipeline'), p.get('category', 'ganzheitlich'),
|
||||
p.get('template'), stages_json, p.get('output_format', 'text'),
|
||||
p.get('output_schema'), p.get('active', True), p.get('sort_order', 0)
|
||||
))
|
||||
created += 1
|
||||
|
||||
conn.commit()
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'created': created,
|
||||
'updated': updated,
|
||||
'skipped': skipped,
|
||||
'errors': errors if errors else None
|
||||
}
|
||||
+16
-3
@@ -7,8 +7,8 @@ Semantic Versioning: MAJOR.MINOR.PATCH
|
||||
- PATCH: Bugfix, kleine Änderung, Refactor
|
||||
"""
|
||||
|
||||
APP_VERSION = "0.9p"
|
||||
BUILD_DATE = "2026-04-09"
|
||||
APP_VERSION = "0.9q"
|
||||
BUILD_DATE = "2026-04-11"
|
||||
DB_SCHEMA_VERSION = "20260409c" # 048/049 vitals_baseline.source csv + SAVEPOINT Import
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
@@ -29,13 +29,26 @@ MODULE_VERSIONS = {
|
||||
"exportdata": "1.1.0",
|
||||
"importdata": "1.0.0",
|
||||
"membership": "2.1.0",
|
||||
"workflow": "0.6.0", # Phase 4: End Node Template Engine
|
||||
"workflow": "0.7.0", # Part 3: Inline Prompts (reference + inline mode)
|
||||
"app_dashboard": "1.11.0", # Entitlements: DB-Override widget→features (AND), sonst Katalog
|
||||
"csv_import": "0.3.2", # Import-Fehler: enrich_row_error / freundlichere 500-Hinweise
|
||||
"admin_csv_templates": "0.3.0", # POST /validate + Speichern nur bei valid (422 + warnings in Response)
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.9q",
|
||||
"date": "2026-04-11",
|
||||
"changes": [
|
||||
"Workflow Engine Part 3: Inline Prompts",
|
||||
"Frontend: Radio Buttons (Reference/Inline), InlineTemplateEditor Component",
|
||||
"Frontend: Placeholder Picker für Inline-Templates, Cursor-Position Tracking",
|
||||
"Backend: load_prompt_template() unterstützt inline_template",
|
||||
"Backend: WorkflowNode.inline_template Feld hinzugefügt",
|
||||
"Serialization: inline_template speichern/laden in graph_data",
|
||||
"Validation: Prüft dass entweder prompt_slug ODER inline_template gesetzt",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.9p",
|
||||
"date": "2026-04-09",
|
||||
|
||||
+110
-22
@@ -18,7 +18,7 @@ import json
|
||||
from jinja2 import Environment, ChainableUndefined, TemplateError
|
||||
|
||||
from workflow_models import (
|
||||
WorkflowGraph, NodeExecutionState, ExecutionResult,
|
||||
WorkflowGraph, WorkflowNode, NodeExecutionState, ExecutionResult,
|
||||
NodeStatus, NormalizedSignal, FallbackStrategy, SignalStatus,
|
||||
EndNodeOutputMode
|
||||
)
|
||||
@@ -278,9 +278,10 @@ async def execute_node(
|
||||
|
||||
# Analysis Nodes
|
||||
if node.type == "analysis":
|
||||
# 1. Lade Prompt
|
||||
prompt_template = await load_prompt_template(node.prompt_slug, context)
|
||||
logger.debug(f"Node {node.id}: Loaded prompt '{node.prompt_slug}'")
|
||||
# 1. Lade Prompt (Part 3: inline_template support)
|
||||
prompt_template = await load_prompt_template(node, context)
|
||||
source_type = "inline" if node.inline_template else "reference"
|
||||
logger.debug(f"Node {node.id}: Loaded prompt from {source_type}")
|
||||
|
||||
# 2. Parse question_augmentations
|
||||
questions = []
|
||||
@@ -593,10 +594,20 @@ def execute_end_node(
|
||||
# AUTO mode: Concatenate all analysis_core values
|
||||
logger.debug(f"End node {node.id}: Using AUTO output mode")
|
||||
|
||||
# Get graph from context for node label lookup
|
||||
graph = context.get("graph")
|
||||
|
||||
combined_analysis = []
|
||||
for node_id, node_state in context.get("node_results", {}).items():
|
||||
if node_state.status == NodeStatus.EXECUTED and node_state.analysis_core:
|
||||
combined_analysis.append(f"## {node_id}\n{node_state.analysis_core}")
|
||||
# Get node label from graph (fallback to node_id if not found)
|
||||
node_label = node_id # default
|
||||
if graph:
|
||||
node_obj = next((n for n in graph.nodes if n.id == node_id), None)
|
||||
if node_obj and hasattr(node_obj, 'data') and node_obj.data:
|
||||
node_label = node_obj.data.get('label', node_id)
|
||||
|
||||
combined_analysis.append(f"## {node_label}\n{node_state.analysis_core}")
|
||||
|
||||
final_output = "\n\n".join(combined_analysis) if combined_analysis else "[No analysis generated]"
|
||||
|
||||
@@ -812,39 +823,64 @@ def _has_active_incoming_edge(node, graph: WorkflowGraph, context: Dict[str, Any
|
||||
return False
|
||||
|
||||
|
||||
async def load_prompt_template(prompt_slug: str, context: Dict[str, Any]) -> str:
|
||||
async def load_prompt_template(node: WorkflowNode, context: Dict[str, Any]) -> str:
|
||||
"""
|
||||
Lädt Prompt-Template aus DB und resolved Platzhalter.
|
||||
Lädt Prompt-Template aus DB (reference mode) oder direkt vom Node (inline mode).
|
||||
|
||||
Part 3: Inline Prompts - Unterstützt zwei Modi:
|
||||
- Reference Mode: prompt_slug → Template aus ai_prompts Tabelle
|
||||
- Inline Mode: inline_template → Template direkt vom Node
|
||||
|
||||
Args:
|
||||
prompt_slug: Slug des Prompts (z.B. "pipeline_body")
|
||||
node: WorkflowNode mit prompt_slug ODER inline_template
|
||||
context: {"variables": {"name": "Lars", ...}, "profile_id": "..."}
|
||||
|
||||
Returns:
|
||||
Resolved prompt template
|
||||
|
||||
Raises:
|
||||
HTTPException: Wenn weder prompt_slug noch inline_template gesetzt
|
||||
|
||||
Beispiel:
|
||||
>>> template = await load_prompt_template("pipeline_body", {"profile_id": "123"})
|
||||
>>> node = WorkflowNode(id="n1", prompt_slug="pipeline_body")
|
||||
>>> template = await load_prompt_template(node, {"profile_id": "123"})
|
||||
>>> "{{name}}" not in template
|
||||
True
|
||||
"""
|
||||
from placeholder_resolver import get_placeholder_example_values, get_placeholder_catalog
|
||||
from prompt_executor import resolve_placeholders
|
||||
from fastapi import HTTPException
|
||||
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT template FROM ai_prompts WHERE slug = %s AND active = true",
|
||||
(prompt_slug,)
|
||||
# Mode 1: Inline Template (NEU)
|
||||
if node.inline_template:
|
||||
logger.debug(f"Node {node.id}: Using inline template ({len(node.inline_template)} chars)")
|
||||
template = node.inline_template
|
||||
|
||||
# Mode 2: Reference (bestehend)
|
||||
elif node.prompt_slug:
|
||||
logger.debug(f"Node {node.id}: Loading prompt '{node.prompt_slug}' from DB")
|
||||
with get_db() as conn:
|
||||
cur = get_cursor(conn)
|
||||
cur.execute(
|
||||
"SELECT template FROM ai_prompts WHERE slug = %s AND active = true",
|
||||
(node.prompt_slug,)
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail=f"Prompt not found: {node.prompt_slug}")
|
||||
template = row['template']
|
||||
|
||||
# Mode 3: Error - weder inline noch reference
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Node {node.id}: Either prompt_slug or inline_template required"
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if not row:
|
||||
raise ValueError(f"Prompt not found: {prompt_slug}")
|
||||
|
||||
template = row['template']
|
||||
|
||||
# Resolve Placeholders using modern prompt_executor method
|
||||
profile_id = context.get("profile_id")
|
||||
if not profile_id:
|
||||
raise HTTPException(status_code=400, detail="profile_id required in context")
|
||||
|
||||
# Build variables dict with ALL registered placeholders
|
||||
variables = {}
|
||||
@@ -852,14 +888,51 @@ async def load_prompt_template(prompt_slug: str, context: Dict[str, Any]) -> str
|
||||
try:
|
||||
# Get all placeholder values from registry
|
||||
processed_placeholders = get_placeholder_example_values(profile_id)
|
||||
logger.info(f"🔍 DEBUG: Loaded {len(processed_placeholders)} placeholders from registry")
|
||||
logger.info(f"🔍 DEBUG: Sample keys (first 3): {list(processed_placeholders.keys())[:3]}")
|
||||
|
||||
# Remove {{ }} from keys (placeholder_resolver returns them with wrappers)
|
||||
cleaned_placeholders = {
|
||||
key.replace('{{', '').replace('}}', ''): value
|
||||
key.replace('{{', '').replace('}}', '').strip(): value
|
||||
for key, value in processed_placeholders.items()
|
||||
}
|
||||
logger.info(f"🔍 DEBUG: Cleaned keys (first 3): {list(cleaned_placeholders.keys())[:3]}")
|
||||
logger.info(f"🔍 DEBUG: Sample values: name={cleaned_placeholders.get('name')}, age={cleaned_placeholders.get('age')}, geschlecht={cleaned_placeholders.get('geschlecht')}")
|
||||
|
||||
variables.update(cleaned_placeholders)
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load placeholders for workflow: {e}")
|
||||
logger.error(f"❌ CRITICAL: Failed to load placeholders for workflow: {e}", exc_info=True)
|
||||
|
||||
# Add workflow node outputs as placeholders (Part 3: Inline Prompts)
|
||||
# Format: node_id.analysis_core, node_id.signal_xyz, node_id.question_xyz
|
||||
node_results = context.get("node_results", {})
|
||||
if node_results:
|
||||
logger.info(f"🔍 DEBUG: Adding {len(node_results)} node outputs as placeholders")
|
||||
for node_id, node_state in node_results.items():
|
||||
# analysis_core
|
||||
if hasattr(node_state, 'analysis_core') and node_state.analysis_core:
|
||||
key = f"{node_id}.analysis_core"
|
||||
variables[key] = node_state.analysis_core
|
||||
logger.debug(f" Added placeholder: {key} = {node_state.analysis_core[:50]}...")
|
||||
|
||||
# decision_signals (keyed by question ID)
|
||||
if hasattr(node_state, 'decision_signals') and node_state.decision_signals:
|
||||
for signal_id, signal_value in node_state.decision_signals.items():
|
||||
# Signal placeholder: node_id.signal_question_id
|
||||
signal_key = f"{node_id}.signal_{signal_id}"
|
||||
variables[signal_key] = signal_value
|
||||
logger.debug(f" Added placeholder: {signal_key} = {signal_value}")
|
||||
|
||||
# Question texts (from graph metadata if available)
|
||||
# NOTE: Question text placeholders are populated from graph in PlaceholderPicker
|
||||
# Here we only add if available in node_state metadata
|
||||
if hasattr(node_state, 'metadata') and isinstance(node_state.metadata, dict):
|
||||
questions = node_state.metadata.get('questions', [])
|
||||
for q in questions:
|
||||
if isinstance(q, dict) and 'id' in q and 'question' in q:
|
||||
question_key = f"{node_id}.question_{q['id']}"
|
||||
variables[question_key] = q['question']
|
||||
logger.debug(f" Added placeholder: {question_key}")
|
||||
|
||||
# Load catalog for |d modifier support
|
||||
try:
|
||||
@@ -868,13 +941,22 @@ async def load_prompt_template(prompt_slug: str, context: Dict[str, Any]) -> str
|
||||
catalog = None
|
||||
logger.warning(f"Failed to load placeholder catalog for workflow: {e}")
|
||||
|
||||
logger.info(f"🔍 DEBUG: Template before resolution:\n{template[:200]}...")
|
||||
logger.info(f"🔍 DEBUG: Variables dict has {len(variables)} entries")
|
||||
|
||||
# Resolve with modern executor
|
||||
debug_info = {}
|
||||
resolved = resolve_placeholders(
|
||||
template=template,
|
||||
variables=variables,
|
||||
debug_info=debug_info,
|
||||
catalog=catalog
|
||||
)
|
||||
|
||||
logger.info(f"🔍 DEBUG: Resolved placeholders: {debug_info.get('resolved_placeholders', {})}")
|
||||
logger.info(f"🔍 DEBUG: Unresolved placeholders: {debug_info.get('unresolved_placeholders', [])}")
|
||||
logger.info(f"🔍 DEBUG: Template after resolution:\n{resolved[:200]}...")
|
||||
|
||||
return resolved
|
||||
|
||||
|
||||
@@ -927,7 +1009,13 @@ def aggregate_results(node_states: List[NodeExecutionState], graph) -> Dict[str,
|
||||
final_output = state.analysis_core
|
||||
else:
|
||||
# Regular node - add to combined analysis
|
||||
combined_analysis.append(f"## {state.node_id}\n{state.analysis_core}")
|
||||
# Get node label from graph (fallback to node_id)
|
||||
node_label = state.node_id # default
|
||||
node_obj = next((n for n in graph.nodes if n.id == state.node_id), None)
|
||||
if node_obj and hasattr(node_obj, 'data') and node_obj.data:
|
||||
node_label = node_obj.data.get('label', state.node_id)
|
||||
|
||||
combined_analysis.append(f"## {node_label}\n{state.analysis_core}")
|
||||
|
||||
if state.normalized_signals:
|
||||
all_signals.extend([s.model_dump() for s in state.normalized_signals])
|
||||
|
||||
@@ -190,7 +190,8 @@ class WorkflowNode(BaseModel):
|
||||
position: Optional[Position] = Field(None, description="Position im visuellen Editor")
|
||||
|
||||
# ANALYSIS-Knoten
|
||||
prompt_slug: Optional[str] = Field(None, description="Slug des auszuführenden Prompts")
|
||||
prompt_slug: Optional[str] = Field(None, description="Slug des auszuführenden Prompts (reference mode)")
|
||||
inline_template: Optional[str] = Field(None, description="Inline-Prompt-Template (inline mode, Part 3)")
|
||||
question_augmentations: Optional[List[QuestionAugmentation]] = Field(None, description="Fragenergänzungen (knotengebunden, überschreiben Prompt-Defaults)")
|
||||
|
||||
# LOGIC-Knoten
|
||||
|
||||
+13
-3
@@ -18,6 +18,8 @@
|
||||
--header-h: 52px;
|
||||
--font: system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
--capture-content-max: 800px;
|
||||
/* Admin: nutzt volle Hauptspalte bis zu dieser Obergrenze (siehe .app-main:has(.admin-shell)) */
|
||||
--admin-main-max: min(1560px, calc(100vw - 220px));
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
@@ -619,13 +621,16 @@ a.analysis-split__nav-item {
|
||||
|
||||
.admin-page {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* Desktop: volle Breite der Admin-Spalte (nicht wie Erfassung 800px); Lesegröße leicht skaliert */
|
||||
@media (min-width: 1024px) {
|
||||
.admin-page {
|
||||
max-width: var(--capture-content-max);
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
max-width: 100%;
|
||||
margin-left: 0;
|
||||
margin-right: 0;
|
||||
font-size: clamp(15px, 0.88rem + 0.25vw, 18px);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -841,6 +846,11 @@ a.analysis-split__nav-item {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Admin: mehr horizontaler Raum für Tabellen auf großen Screens (:has ~2022+, sonst bleibt 1200px) */
|
||||
.app-main:has(.admin-shell) {
|
||||
max-width: var(--admin-main-max);
|
||||
}
|
||||
|
||||
/* Dashboard (P3): Begrüßung + Kennzahlen-Zeile */
|
||||
.dashboard-greeting {
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* ConfirmDialog Component
|
||||
*
|
||||
* Modal confirmation dialog
|
||||
*
|
||||
* Props:
|
||||
* - message: string
|
||||
* - onConfirm: callback when confirmed
|
||||
* - onCancel: callback when cancelled
|
||||
* - confirmText: string (default: 'OK')
|
||||
* - cancelText: string (default: 'Abbrechen')
|
||||
* - type: 'warning' | 'danger' | 'info' (default: 'warning')
|
||||
*/
|
||||
export function ConfirmDialog({
|
||||
message,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
confirmText = 'OK',
|
||||
cancelText = 'Abbrechen',
|
||||
type = 'warning'
|
||||
}) {
|
||||
const colors = {
|
||||
warning: '#FFC107',
|
||||
danger: 'var(--danger)',
|
||||
info: 'var(--accent)'
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 20000
|
||||
}}
|
||||
onClick={onCancel}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
background: 'var(--surface)',
|
||||
borderRadius: '12px',
|
||||
padding: '24px',
|
||||
maxWidth: '500px',
|
||||
width: '90%',
|
||||
boxShadow: '0 8px 24px rgba(0,0,0,0.3)'
|
||||
}}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
fontSize: '16px',
|
||||
marginBottom: '24px',
|
||||
color: 'var(--text1)',
|
||||
lineHeight: '1.5'
|
||||
}}
|
||||
>
|
||||
{message}
|
||||
</div>
|
||||
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: '12px',
|
||||
justifyContent: 'flex-end'
|
||||
}}
|
||||
>
|
||||
<button
|
||||
onClick={onCancel}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: '6px',
|
||||
background: 'var(--surface2)',
|
||||
color: 'var(--text1)',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px'
|
||||
}}
|
||||
>
|
||||
{cancelText}
|
||||
</button>
|
||||
<button
|
||||
onClick={onConfirm}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
border: 'none',
|
||||
borderRadius: '6px',
|
||||
background: colors[type],
|
||||
color: type === 'warning' ? '#000' : 'white',
|
||||
cursor: 'pointer',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500
|
||||
}}
|
||||
>
|
||||
{confirmText}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { useEffect } from 'react'
|
||||
|
||||
/**
|
||||
* Toast Notification Component
|
||||
*
|
||||
* Auto-closing notification that appears at the top of the screen
|
||||
*
|
||||
* Props:
|
||||
* - message: string
|
||||
* - type: 'success' | 'error' | 'warning' | 'info'
|
||||
* - duration: number (ms, default 3000)
|
||||
* - onClose: callback when toast closes
|
||||
*/
|
||||
export function Toast({ message, type = 'info', duration = 3000, onClose }) {
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
if (onClose) onClose()
|
||||
}, duration)
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}, [duration, onClose])
|
||||
|
||||
const styles = {
|
||||
success: {
|
||||
background: '#4CAF50',
|
||||
color: 'white',
|
||||
icon: '✅'
|
||||
},
|
||||
error: {
|
||||
background: 'var(--danger)',
|
||||
color: 'white',
|
||||
icon: '❌'
|
||||
},
|
||||
warning: {
|
||||
background: '#FFC107',
|
||||
color: '#856404',
|
||||
icon: '⚠️'
|
||||
},
|
||||
info: {
|
||||
background: 'var(--accent)',
|
||||
color: 'white',
|
||||
icon: 'ℹ️'
|
||||
}
|
||||
}
|
||||
|
||||
const style = styles[type] || styles.info
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
top: '80px',
|
||||
left: '50%',
|
||||
transform: 'translateX(-50%)',
|
||||
background: style.background,
|
||||
color: style.color,
|
||||
padding: '12px 24px',
|
||||
borderRadius: '8px',
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.3)',
|
||||
zIndex: 10000,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '8px',
|
||||
fontSize: '14px',
|
||||
fontWeight: 500,
|
||||
minWidth: '300px',
|
||||
maxWidth: '600px',
|
||||
animation: 'slideDown 0.3s ease-out'
|
||||
}}
|
||||
onClick={onClose}
|
||||
>
|
||||
<span style={{ fontSize: '18px' }}>{style.icon}</span>
|
||||
<span>{message}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Add animation CSS if not already in global styles
|
||||
const styleElement = document.createElement('style')
|
||||
styleElement.textContent = `
|
||||
@keyframes slideDown {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(-50%) translateY(-20px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(-50%) translateY(0);
|
||||
}
|
||||
}
|
||||
`
|
||||
if (!document.querySelector('style[data-toast-styles]')) {
|
||||
styleElement.setAttribute('data-toast-styles', 'true')
|
||||
document.head.appendChild(styleElement)
|
||||
}
|
||||
@@ -39,6 +39,7 @@ export function WorkflowCanvas({
|
||||
className="workflow-canvas"
|
||||
minZoom={0.2}
|
||||
maxZoom={2}
|
||||
deleteKeyCode={['Backspace', 'Delete']}
|
||||
defaultEdgeOptions={{
|
||||
animated: false,
|
||||
style: { strokeWidth: 2 },
|
||||
|
||||
@@ -5,16 +5,22 @@ import { Handle, Position } from 'reactflow'
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label
|
||||
* - data.prompt_slug: Slug des referenzierten Basis-Prompts
|
||||
* - data.prompt_slug: Slug des referenzierten Basis-Prompts (Reference Mode)
|
||||
* - data.inline_template: Inline Prompt-Template (Inline Mode)
|
||||
* - 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_slug ? `Prompt: ${data.prompt_slug}` : 'Kein Prompt')
|
||||
const questionCount = data.questions?.length || 0
|
||||
|
||||
// Part 3: Inline Prompts - Zeige "Inline-Template" oder Prompt-Namen
|
||||
const isInlineMode = data.inline_template !== null && data.inline_template !== undefined
|
||||
const promptName = isInlineMode
|
||||
? '✏️ Inline-Template'
|
||||
: (data.prompt_name || (data.prompt_slug ? `Prompt: ${data.prompt_slug}` : 'Kein Prompt'))
|
||||
|
||||
return (
|
||||
<div className={`workflow-node analysis-node ${selected ? 'selected' : ''}`}>
|
||||
<div className="node-header">
|
||||
|
||||
@@ -42,24 +42,54 @@ export function JoinNode({ data, selected }) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Mehrere Target Handles für eingehende Pfade */}
|
||||
{/* Mehrere Target Handles für eingehende Pfade (bis zu 8) */}
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_1"
|
||||
style={{ left: '25%', background: '#17A2B8' }}
|
||||
style={{ left: '11%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_2"
|
||||
style={{ left: '50%', background: '#17A2B8' }}
|
||||
style={{ left: '22%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_3"
|
||||
style={{ left: '75%', background: '#17A2B8' }}
|
||||
style={{ left: '33%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_4"
|
||||
style={{ left: '44%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_5"
|
||||
style={{ left: '56%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_6"
|
||||
style={{ left: '67%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_7"
|
||||
style={{ left: '78%', background: '#17A2B8' }}
|
||||
/>
|
||||
<Handle
|
||||
type="target"
|
||||
position={Position.Top}
|
||||
id="path_8"
|
||||
style={{ left: '89%', background: '#17A2B8' }}
|
||||
/>
|
||||
|
||||
{/* Ein Source Handle für konsolidierten Ausgang */}
|
||||
|
||||
@@ -3,9 +3,8 @@ import { Handle, Position } from 'reactflow'
|
||||
/**
|
||||
* StartNode - Workflow Einstiegspunkt
|
||||
*
|
||||
* Properties:
|
||||
* - data.label: Node-Label (default: "Start")
|
||||
* - selected: Boolean (Node ist ausgewählt)
|
||||
* - data.label: Anzeige auf dem Canvas (Node-Name)
|
||||
* - data.analysis_title: nur für KI-Analyse-UI, nicht auf dem Canvas
|
||||
*/
|
||||
export function StartNode({ data, selected }) {
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { useRef } from 'react'
|
||||
|
||||
/**
|
||||
* InlineTemplateEditor - Template-Editor für Inline-Prompts
|
||||
*
|
||||
* Props:
|
||||
* - value: Template-String
|
||||
* - onChange: (template) => void
|
||||
* - onPlaceholderPick: () => void - Öffnet Placeholder Picker
|
||||
* - textareaRef: Ref für Cursor-Position (von Parent)
|
||||
*/
|
||||
export function InlineTemplateEditor({ value, onChange, onPlaceholderPick, textareaRef }) {
|
||||
return (
|
||||
<div className="inline-template-editor" style={{ marginTop: '12px' }}>
|
||||
<label className="form-label">Template</label>
|
||||
<div style={{ position: 'relative' }}>
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={value || ''}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
placeholder="Analysiere folgende Daten: Gewicht: {{ weight_current }} Ziel: {{ goal_weight }} Gib eine Empfehlung..."
|
||||
rows={12}
|
||||
style={{
|
||||
width: '100%',
|
||||
fontFamily: 'monospace',
|
||||
fontSize: '13px',
|
||||
padding: '12px',
|
||||
paddingRight: '120px', // Platz für Button
|
||||
borderRadius: '8px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--bg)',
|
||||
color: 'var(--text1)',
|
||||
resize: 'vertical',
|
||||
lineHeight: '1.5'
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
className="btn-secondary"
|
||||
onClick={onPlaceholderPick}
|
||||
style={{
|
||||
position: 'absolute',
|
||||
top: '8px',
|
||||
right: '8px',
|
||||
fontSize: '11px',
|
||||
padding: '6px 10px',
|
||||
whiteSpace: 'nowrap'
|
||||
}}
|
||||
>
|
||||
{'{{ }}'} Platzhalter
|
||||
</button>
|
||||
</div>
|
||||
<div
|
||||
className="help-text"
|
||||
style={{
|
||||
fontSize: '12px',
|
||||
color: 'var(--text3)',
|
||||
marginTop: '6px'
|
||||
}}
|
||||
>
|
||||
💡 Tipp: Verwende <code style={{
|
||||
background: 'var(--surface2)',
|
||||
padding: '2px 6px',
|
||||
borderRadius: '4px',
|
||||
fontFamily: 'monospace'
|
||||
}}>{'{{ placeholder_name }}'}</code> für dynamische Werte
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -6,17 +6,19 @@ import { api } from '../../../utils/api'
|
||||
*
|
||||
* Props:
|
||||
* - nodes: Array of workflow nodes (to extract workflow-specific placeholders)
|
||||
* - currentNodeId: ID des aktuellen Nodes (wird aus Placeholders ausgeschlossen)
|
||||
* - onSelect: (placeholderString) => void - Callback when placeholder is selected
|
||||
* - onClose: () => void
|
||||
*
|
||||
* Features:
|
||||
* - Lädt registrierte Platzhalter vom Backend (~120+)
|
||||
* - Extrahiert Workflow-spezifische Node-Outputs
|
||||
* - Filtert Selbst-Referenzierung (Node kann sich nicht selbst referenzieren)
|
||||
* - Zeigt Node-Namen (nicht nur IDs)
|
||||
* - Kategorisiert: System + Workflow
|
||||
* - Suchfunktion über alle Kategorien
|
||||
*/
|
||||
export function PlaceholderPicker({ nodes, onSelect, onClose }) {
|
||||
export function PlaceholderPicker({ nodes, currentNodeId, onSelect, onClose }) {
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [systemPlaceholders, setSystemPlaceholders] = useState([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
@@ -61,8 +63,8 @@ export function PlaceholderPicker({ nodes, onSelect, onClose }) {
|
||||
loadPlaceholders()
|
||||
}, [])
|
||||
|
||||
// Extrahiere Workflow-spezifische Platzhalter
|
||||
const workflowPlaceholders = extractWorkflowPlaceholders(nodes)
|
||||
// Extrahiere Workflow-spezifische Platzhalter (ohne aktuellen Node)
|
||||
const workflowPlaceholders = extractWorkflowPlaceholders(nodes, currentNodeId)
|
||||
|
||||
// Kombiniere beide Listen
|
||||
const allPlaceholders = [
|
||||
@@ -341,14 +343,19 @@ export function PlaceholderPicker({ nodes, onSelect, onClose }) {
|
||||
|
||||
/**
|
||||
* Extrahiert Workflow-spezifische Platzhalter aus Nodes
|
||||
*
|
||||
* @param {Array} nodes - Alle Workflow-Nodes
|
||||
* @param {string} currentNodeId - ID des aktuellen Nodes (wird ausgeschlossen)
|
||||
*/
|
||||
function extractWorkflowPlaceholders(nodes) {
|
||||
function extractWorkflowPlaceholders(nodes, currentNodeId) {
|
||||
const placeholders = []
|
||||
|
||||
console.log('🔍 Extracting workflow placeholders from nodes:', nodes)
|
||||
console.log('🚫 Excluding current node:', currentNodeId)
|
||||
|
||||
nodes.forEach(node => {
|
||||
if (node.type === 'end') return // End Node hat keine Outputs
|
||||
if (node.id === currentNodeId) return // Selbst-Referenzierung verhindern
|
||||
|
||||
const nodeId = node.id
|
||||
const nodeLabel = node.data?.label || nodeId
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
import { useState } from 'react'
|
||||
import { AlertCircle, AlertTriangle, ChevronDown, ChevronRight, X } from 'lucide-react'
|
||||
|
||||
/**
|
||||
* ValidationPanel - Zeigt Fehler und Warnungen mit Details
|
||||
*
|
||||
* Features:
|
||||
* - Aufklappbar (collapsible)
|
||||
* - Click-to-Jump zu betroffener Node
|
||||
* - Gruppierung nach Severity
|
||||
* - Klare visuelle Trennung
|
||||
*/
|
||||
export function ValidationPanel({ errors, warnings, onNodeClick, onClose }) {
|
||||
const [isExpanded, setIsExpanded] = useState(true)
|
||||
const [showErrors, setShowErrors] = useState(true)
|
||||
const [showWarnings, setShowWarnings] = useState(true)
|
||||
|
||||
const totalCount = errors.length + warnings.length
|
||||
|
||||
if (totalCount === 0) return null
|
||||
|
||||
const handleItemClick = (item) => {
|
||||
if (item.nodeId && onNodeClick) {
|
||||
onNodeClick(item.nodeId)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
position: 'fixed',
|
||||
bottom: 90,
|
||||
right: 20,
|
||||
width: 400,
|
||||
maxHeight: '60vh',
|
||||
background: 'var(--surface)',
|
||||
border: '1px solid var(--border)',
|
||||
borderRadius: 8,
|
||||
boxShadow: '0 4px 12px rgba(0,0,0,0.15)',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
zIndex: 100
|
||||
}}>
|
||||
{/* Header */}
|
||||
<div
|
||||
onClick={() => setIsExpanded(!isExpanded)}
|
||||
style={{
|
||||
padding: '12px 16px',
|
||||
borderBottom: isExpanded ? '1px solid var(--border)' : 'none',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
cursor: 'pointer',
|
||||
userSelect: 'none',
|
||||
background: errors.length > 0 ? 'rgba(216, 90, 48, 0.1)' : 'rgba(255, 193, 7, 0.1)'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
|
||||
{isExpanded ? <ChevronDown size={18} /> : <ChevronRight size={18} />}
|
||||
<AlertCircle size={18} color={errors.length > 0 ? 'var(--danger)' : '#f59e0b'} />
|
||||
<span style={{ fontWeight: 600, fontSize: 14 }}>
|
||||
Validierung
|
||||
</span>
|
||||
<span style={{ fontSize: 12, color: 'var(--text3)' }}>
|
||||
{errors.length > 0 && `${errors.length} Fehler`}
|
||||
{errors.length > 0 && warnings.length > 0 && ', '}
|
||||
{warnings.length > 0 && `${warnings.length} Warnung${warnings.length > 1 ? 'en' : ''}`}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onClose && onClose()
|
||||
}}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
cursor: 'pointer',
|
||||
padding: 4,
|
||||
display: 'flex',
|
||||
alignItems: 'center'
|
||||
}}
|
||||
>
|
||||
<X size={16} color="var(--text3)" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
{isExpanded && (
|
||||
<div style={{
|
||||
overflowY: 'auto',
|
||||
maxHeight: 'calc(60vh - 60px)'
|
||||
}}>
|
||||
{/* Errors */}
|
||||
{errors.length > 0 && (
|
||||
<div>
|
||||
<div
|
||||
onClick={() => setShowErrors(!showErrors)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
background: 'rgba(216, 90, 48, 0.05)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
cursor: 'pointer',
|
||||
userSelect: 'none',
|
||||
borderBottom: '1px solid var(--border)'
|
||||
}}
|
||||
>
|
||||
{showErrors ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
<AlertCircle size={16} color="var(--danger)" />
|
||||
<span style={{ fontWeight: 600, fontSize: 13, color: 'var(--danger)' }}>
|
||||
Fehler ({errors.length})
|
||||
</span>
|
||||
</div>
|
||||
{showErrors && (
|
||||
<div>
|
||||
{errors.map((error, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
onClick={() => handleItemClick(error)}
|
||||
style={{
|
||||
padding: '10px 16px',
|
||||
borderBottom: idx < errors.length - 1 ? '1px solid var(--border)' : 'none',
|
||||
cursor: error.nodeId ? 'pointer' : 'default',
|
||||
background: error.nodeId ? 'transparent' : 'transparent',
|
||||
transition: 'background 0.15s',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (error.nodeId) e.currentTarget.style.background = 'rgba(216, 90, 48, 0.05)'
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'transparent'
|
||||
}}
|
||||
>
|
||||
<div style={{
|
||||
fontSize: 13,
|
||||
color: 'var(--text1)',
|
||||
marginBottom: 4
|
||||
}}>
|
||||
{error.message}
|
||||
</div>
|
||||
{error.nodeId && (
|
||||
<div style={{
|
||||
fontSize: 11,
|
||||
color: 'var(--text3)',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
→ Klicken um zu Node zu springen
|
||||
</div>
|
||||
)}
|
||||
{error.type && (
|
||||
<div style={{
|
||||
fontSize: 10,
|
||||
color: 'var(--text3)',
|
||||
marginTop: 4,
|
||||
textTransform: 'uppercase'
|
||||
}}>
|
||||
{error.type}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Warnings */}
|
||||
{warnings.length > 0 && (
|
||||
<div>
|
||||
<div
|
||||
onClick={() => setShowWarnings(!showWarnings)}
|
||||
style={{
|
||||
padding: '8px 16px',
|
||||
background: 'rgba(255, 193, 7, 0.05)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
cursor: 'pointer',
|
||||
userSelect: 'none',
|
||||
borderBottom: '1px solid var(--border)'
|
||||
}}
|
||||
>
|
||||
{showWarnings ? <ChevronDown size={16} /> : <ChevronRight size={16} />}
|
||||
<AlertTriangle size={16} color="#f59e0b" />
|
||||
<span style={{ fontWeight: 600, fontSize: 13, color: '#f59e0b' }}>
|
||||
Warnungen ({warnings.length})
|
||||
</span>
|
||||
</div>
|
||||
{showWarnings && (
|
||||
<div>
|
||||
{warnings.map((warning, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
onClick={() => handleItemClick(warning)}
|
||||
style={{
|
||||
padding: '10px 16px',
|
||||
borderBottom: idx < warnings.length - 1 ? '1px solid var(--border)' : 'none',
|
||||
cursor: warning.nodeId ? 'pointer' : 'default',
|
||||
background: 'transparent',
|
||||
transition: 'background 0.15s',
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (warning.nodeId) e.currentTarget.style.background = 'rgba(255, 193, 7, 0.05)'
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
e.currentTarget.style.background = 'transparent'
|
||||
}}
|
||||
>
|
||||
<div style={{
|
||||
fontSize: 13,
|
||||
color: 'var(--text1)',
|
||||
marginBottom: 4
|
||||
}}>
|
||||
{warning.message}
|
||||
</div>
|
||||
{warning.nodeId && (
|
||||
<div style={{
|
||||
fontSize: 11,
|
||||
color: 'var(--text3)',
|
||||
fontFamily: 'monospace'
|
||||
}}>
|
||||
→ Klicken um zu Node zu springen
|
||||
</div>
|
||||
)}
|
||||
{warning.type && (
|
||||
<div style={{
|
||||
fontSize: 10,
|
||||
color: 'var(--text3)',
|
||||
marginTop: 4,
|
||||
textTransform: 'uppercase'
|
||||
}}>
|
||||
{warning.type}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/** DB `ai_prompts.category` – Reihenfolge der Gruppen in der KI-Analyse-Navigation */
|
||||
|
||||
export const ANALYSIS_CATEGORY_ORDER = [
|
||||
'körper',
|
||||
'ernährung',
|
||||
'training',
|
||||
'schlaf',
|
||||
'vitalwerte',
|
||||
'ziele',
|
||||
'ganzheitlich',
|
||||
]
|
||||
|
||||
export const ANALYSIS_CATEGORY_LABELS = {
|
||||
körper: 'Körper',
|
||||
ernährung: 'Ernährung',
|
||||
training: 'Training',
|
||||
schlaf: 'Schlaf',
|
||||
vitalwerte: 'Vitalwerte',
|
||||
ziele: 'Ziele',
|
||||
ganzheitlich: 'Ganzheitlich',
|
||||
}
|
||||
@@ -21,6 +21,7 @@ export default function AdminPromptsPage() {
|
||||
const [showNewPrompt, setShowNewPrompt] = useState(false)
|
||||
const [importing, setImporting] = useState(false)
|
||||
const [importResult, setImportResult] = useState(null)
|
||||
const [importDialogData, setImportDialogData] = useState(null) // {count, fileData, event}
|
||||
|
||||
const categories = [
|
||||
{ id: 'all', label: 'Alle Kategorien' },
|
||||
@@ -194,7 +195,6 @@ export default function AdminPromptsPage() {
|
||||
const file = event.target.files[0]
|
||||
if (!file) return
|
||||
|
||||
setImporting(true)
|
||||
setError(null)
|
||||
setImportResult(null)
|
||||
|
||||
@@ -202,14 +202,34 @@ export default function AdminPromptsPage() {
|
||||
const text = await file.text()
|
||||
const data = JSON.parse(text)
|
||||
|
||||
// Ask user about overwrite
|
||||
const overwrite = confirm(
|
||||
'Bestehende Prompts überschreiben?\n\n' +
|
||||
'JA = Existierende Prompts aktualisieren\n' +
|
||||
'NEIN = Nur neue Prompts erstellen, Duplikate überspringen'
|
||||
)
|
||||
// Show custom 3-button dialog
|
||||
setImportDialogData({
|
||||
count: data.count || 0,
|
||||
fileData: data,
|
||||
event: event
|
||||
})
|
||||
} catch (e) {
|
||||
setError('Import-Fehler: ' + e.message)
|
||||
event.target.value = '' // Reset file input
|
||||
}
|
||||
}
|
||||
|
||||
const result = await api.importPrompts(data, overwrite)
|
||||
const handleImportChoice = async (choice) => {
|
||||
if (!importDialogData) return
|
||||
|
||||
const { fileData, event } = importDialogData
|
||||
setImportDialogData(null) // Close dialog
|
||||
|
||||
if (choice === 'cancel') {
|
||||
event.target.value = '' // Reset file input
|
||||
return
|
||||
}
|
||||
|
||||
setImporting(true)
|
||||
|
||||
try {
|
||||
const overwrite = choice === 'yes' // 'yes' = overwrite, 'no' = skip existing
|
||||
const result = await api.importPrompts(fileData, overwrite)
|
||||
setImportResult(result)
|
||||
await loadPrompts()
|
||||
} catch (e) {
|
||||
@@ -607,6 +627,70 @@ export default function AdminPromptsPage() {
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Import Dialog - 3 Button Choice */}
|
||||
{importDialogData && (
|
||||
<div style={{
|
||||
position: 'fixed',
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
background: 'rgba(0,0,0,0.5)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
zIndex: 9999
|
||||
}}>
|
||||
<div style={{
|
||||
background: 'var(--bg)',
|
||||
borderRadius: 12,
|
||||
padding: 24,
|
||||
maxWidth: 500,
|
||||
width: '90%',
|
||||
boxShadow: '0 4px 20px rgba(0,0,0,0.2)'
|
||||
}}>
|
||||
<h3 style={{ marginTop: 0, marginBottom: 16, fontSize: 18 }}>
|
||||
{importDialogData.count} Prompts importieren?
|
||||
</h3>
|
||||
<p style={{ marginBottom: 24, color: 'var(--text2)', lineHeight: 1.5 }}>
|
||||
Wie sollen existierende Prompts behandelt werden?
|
||||
</p>
|
||||
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
|
||||
<button
|
||||
className="btn btn-primary"
|
||||
onClick={() => handleImportChoice('yes')}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
Ja, überschreiben
|
||||
<div style={{ fontSize: 12, opacity: 0.8, marginTop: 4 }}>
|
||||
Bestehende Prompts aktualisieren
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="btn"
|
||||
onClick={() => handleImportChoice('no')}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
Nein, nur neue
|
||||
<div style={{ fontSize: 12, opacity: 0.8, marginTop: 4 }}>
|
||||
Nur neue Prompts erstellen, bestehende überspringen
|
||||
</div>
|
||||
</button>
|
||||
|
||||
<button
|
||||
className="btn btn-secondary"
|
||||
onClick={() => handleImportChoice('cancel')}
|
||||
style={{ width: '100%' }}
|
||||
>
|
||||
Abbrechen
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -2,6 +2,11 @@ import React, { useState, useEffect, useMemo } from 'react'
|
||||
import { Brain, Trash2, ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { api } from '../utils/api'
|
||||
import { getWorkflowDisplayContent } from '../utils/workflowDisplay'
|
||||
import {
|
||||
ANALYSIS_CATEGORY_ORDER,
|
||||
ANALYSIS_CATEGORY_LABELS,
|
||||
} from '../config/analysisCategories'
|
||||
import { useAuth } from '../context/AuthContext'
|
||||
import Markdown from '../utils/Markdown'
|
||||
import UsageBadge from '../components/UsageBadge'
|
||||
@@ -14,19 +19,6 @@ const SLUG_LABELS = {
|
||||
pipeline: '🔬 Mehrstufige Gesamtanalyse'
|
||||
}
|
||||
|
||||
/** DB `ai_prompts.category` – Reihenfolge der Gruppen in der Analyse-Navigation */
|
||||
const ANALYSIS_CATEGORY_ORDER = ['körper', 'ernährung', 'training', 'schlaf', 'vitalwerte', 'ziele', 'ganzheitlich']
|
||||
|
||||
const ANALYSIS_CATEGORY_LABELS = {
|
||||
körper: 'Körper',
|
||||
ernährung: 'Ernährung',
|
||||
training: 'Training',
|
||||
schlaf: 'Schlaf',
|
||||
vitalwerte: 'Vitalwerte',
|
||||
ziele: 'Ziele',
|
||||
ganzheitlich: 'Ganzheitlich',
|
||||
}
|
||||
|
||||
function sortAnalysisCategoryKeys(keys) {
|
||||
return [...keys].sort((a, b) => {
|
||||
const na = String(a).toLowerCase()
|
||||
@@ -45,6 +37,11 @@ function analysisCategoryLabel(key) {
|
||||
return ANALYSIS_CATEGORY_LABELS[k] || String(key)
|
||||
}
|
||||
|
||||
/** Analyse-Angebote: klassische Pipelines + graphbasierte KI-Workflows (`type === 'workflow'`) */
|
||||
function isAnalysisOfferPrompt(p) {
|
||||
return p.active && (p.type === 'pipeline' || p.type === 'workflow')
|
||||
}
|
||||
|
||||
/** Pipeline-Prompts nach `category` gruppieren (Backend-Feld), innerhalb Gruppe nach sort_order */
|
||||
function buildPipelineGroups(pipelinePrompts) {
|
||||
const m = new Map()
|
||||
@@ -81,7 +78,8 @@ function InsightCard({ ins, onDelete, defaultOpen=false, prompts=[] }) {
|
||||
|
||||
// Find matching prompt to get display_name
|
||||
const prompt = prompts.find(p => p.slug === ins.scope)
|
||||
const displayName = prompt?.display_name || SLUG_LABELS[ins.scope] || ins.scope
|
||||
const displayName =
|
||||
prompt?.display_name || prompt?.name || SLUG_LABELS[ins.scope] || ins.scope
|
||||
|
||||
// Use already-parsed metadata
|
||||
const metadata = metadataRaw
|
||||
@@ -360,7 +358,7 @@ export default function Analysis() {
|
||||
},[])
|
||||
|
||||
useEffect(() => {
|
||||
const list = prompts.filter(p => p.active && p.type === 'pipeline')
|
||||
const list = prompts.filter(isAnalysisOfferPrompt)
|
||||
setActiveCategoryKey(prev => {
|
||||
if (!list.length) return null
|
||||
const groups = buildPipelineGroups(list)
|
||||
@@ -372,7 +370,7 @@ export default function Analysis() {
|
||||
|
||||
useEffect(() => {
|
||||
if (!newResult?.scope) return
|
||||
const list = prompts.filter(p => p.active && p.type === 'pipeline')
|
||||
const list = prompts.filter(isAnalysisOfferPrompt)
|
||||
const groups = buildPipelineGroups(list)
|
||||
const g = groups.find(gg => gg.prompts.some(p => p.slug === newResult.scope))
|
||||
if (g) setActiveCategoryKey(g.categoryKey)
|
||||
@@ -394,6 +392,8 @@ export default function Analysis() {
|
||||
} else {
|
||||
content = JSON.stringify(finalOutput, null, 2)
|
||||
}
|
||||
} else if (result.type === 'workflow') {
|
||||
content = getWorkflowDisplayContent(result.aggregated_result)
|
||||
} else {
|
||||
// For base prompts, use output directly
|
||||
content = typeof result.output === 'string' ? result.output : JSON.stringify(result.output, null, 2)
|
||||
@@ -405,7 +405,7 @@ export default function Analysis() {
|
||||
const placeholders = {}
|
||||
const resolved = result.debug.resolved_placeholders
|
||||
|
||||
// For pipeline, collect from all stages
|
||||
// For pipeline, collect from all stages (Workflow: kein gleiches debug-Schema)
|
||||
if (result.type === 'pipeline' && result.debug.stages) {
|
||||
for (const stage of result.debug.stages) {
|
||||
for (const promptDebug of (stage.prompts || [])) {
|
||||
@@ -456,9 +456,9 @@ export default function Analysis() {
|
||||
grouped[key].push(ins)
|
||||
})
|
||||
|
||||
// Show only active pipeline-type prompts (und nach DB-Kategorie gruppiert)
|
||||
// Aktive Pipeline- + Workflow-Prompts (nach DB-Kategorie gruppiert)
|
||||
const { pipelinePrompts, pipelineGroups } = useMemo(() => {
|
||||
const list = prompts.filter(p => p.active && p.type === 'pipeline')
|
||||
const list = prompts.filter(isAnalysisOfferPrompt)
|
||||
return { pipelinePrompts: list, pipelineGroups: buildPipelineGroups(list) }
|
||||
}, [prompts])
|
||||
|
||||
@@ -538,9 +538,10 @@ export default function Analysis() {
|
||||
{canUseAI && pipelinePrompts.length > 0 && (
|
||||
<>
|
||||
<p style={{fontSize:13,color:'var(--text2)',marginBottom:14,lineHeight:1.6}}>
|
||||
Zuerst die <strong>Kategorie</strong> wählen (Chip-Leiste bzw. Seitenleiste). Alle Pipeline-Analysen
|
||||
dieser Kategorie erscheinen im Detailbereich (rechts auf Desktop, darunter auf Mobil).
|
||||
Kategorien kommen aus dem Feld „Kategorie“ beim jeweiligen Prompt im Admin.
|
||||
Zuerst die <strong>Kategorie</strong> wählen (Chip-Leiste bzw. Seitenleiste). Alle{' '}
|
||||
<strong>Pipeline- und Workflow-Auswertungen</strong> dieser Kategorie erscheinen im Detailbereich
|
||||
(rechts auf Desktop, darunter auf Mobil). Bei Workflows legst du Kategorie, Titel und Kurztext in der{' '}
|
||||
<strong>Start-Node</strong> des Workflow-Editors fest; bei Pipelines im Admin unter KI-Prompts.
|
||||
</p>
|
||||
<div className="analysis-split">
|
||||
<div className="analysis-split__nav-wrap">
|
||||
@@ -641,9 +642,9 @@ export default function Analysis() {
|
||||
|
||||
{canUseAI && pipelinePrompts.length === 0 && (
|
||||
<div className="empty-state">
|
||||
<p>Keine aktiven Pipeline-Prompts verfügbar.</p>
|
||||
<p>Keine aktiven Pipeline- oder Workflow-Auswertungen verfügbar.</p>
|
||||
<p style={{fontSize:12,color:'var(--text3)',marginTop:8}}>
|
||||
Erstelle Pipeline-Prompts im Admin-Bereich unter Admin → KI-Prompts.
|
||||
Pipelines und Workflows werden im Admin unter KI-Prompts bzw. Workflow-Editor angelegt.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
@@ -667,7 +668,10 @@ export default function Analysis() {
|
||||
onClick={() => setHistoryScopePick(scope)}
|
||||
aria-current={activeHistoryScope === scope ? 'page' : undefined}
|
||||
>
|
||||
{prompts.find(pr => pr.slug === scope)?.display_name || SLUG_LABELS[scope] || scope}
|
||||
{(() => {
|
||||
const pr = prompts.find((p) => p.slug === scope)
|
||||
return pr?.display_name || pr?.name || SLUG_LABELS[scope] || scope
|
||||
})()}
|
||||
<span className="muted" style={{ fontSize: 12 }}> ({grouped[scope].length})</span>
|
||||
</button>
|
||||
))}
|
||||
|
||||
@@ -18,7 +18,33 @@ import { EndNodeConfig } from '../components/workflow/panels/EndNodeConfig'
|
||||
import { PlaceholderPicker } from '../components/workflow/panels/PlaceholderPicker'
|
||||
import { WorkflowExecutePanel } from '../components/workflow/panels/WorkflowExecutePanel'
|
||||
import { WorkflowResultViewer } from '../components/workflow/panels/WorkflowResultViewer'
|
||||
import { InlineTemplateEditor } from '../components/workflow/panels/InlineTemplateEditor'
|
||||
import { ValidationPanel } from '../components/workflow/panels/ValidationPanel'
|
||||
import { Toast } from '../components/Toast'
|
||||
import { ConfirmDialog } from '../components/ConfirmDialog'
|
||||
import '../styles/workflowEditor.css'
|
||||
import {
|
||||
ANALYSIS_CATEGORY_ORDER,
|
||||
ANALYSIS_CATEGORY_LABELS,
|
||||
} from '../config/analysisCategories'
|
||||
|
||||
/** Aus Start-Node → Felder für Analyse-UI / ai_prompts (display_name, description, category) */
|
||||
function getWorkflowAnalysisPublishFields(nodes, fallbackName) {
|
||||
const start = nodes.find((n) => n.type === 'start')
|
||||
const d = start?.data || {}
|
||||
const title =
|
||||
String(d.analysis_title ?? '').trim() ||
|
||||
String(fallbackName ?? '').trim() ||
|
||||
'Workflow'
|
||||
const description = String(d.analysis_description ?? '').trim()
|
||||
const category =
|
||||
String(d.analysis_category ?? 'ganzheitlich').toLowerCase().trim() || 'ganzheitlich'
|
||||
return {
|
||||
display_name: title,
|
||||
description: description || null,
|
||||
category,
|
||||
}
|
||||
}
|
||||
|
||||
// Node-Type Mapping
|
||||
const nodeTypes = {
|
||||
@@ -42,7 +68,6 @@ export default function WorkflowEditorPage() {
|
||||
const selectedNode = selectedNodeId ? nodes.find(n => n.id === selectedNodeId) : 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)
|
||||
@@ -50,7 +75,26 @@ export default function WorkflowEditorPage() {
|
||||
const [availablePrompts, setAvailablePrompts] = useState([])
|
||||
const [executionResult, setExecutionResult] = useState(null)
|
||||
const [showPlaceholderPicker, setShowPlaceholderPicker] = useState(false)
|
||||
const [placeholderPickerTarget, setPlaceholderPickerTarget] = useState('end') // 'end' | 'inline'
|
||||
const endNodeTextareaRef = useRef(null)
|
||||
const inlineTemplateTextareaRef = useRef(null)
|
||||
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
|
||||
const [showValidationPanel, setShowValidationPanel] = useState(true)
|
||||
|
||||
// Toast & Confirm Dialog
|
||||
const [toast, setToast] = useState(null)
|
||||
const [confirmDialog, setConfirmDialog] = useState(null)
|
||||
|
||||
// Wrapped handlers to track unsaved changes
|
||||
const handleNodesChange = useCallback((changes) => {
|
||||
onNodesChange(changes)
|
||||
setHasUnsavedChanges(true)
|
||||
}, [onNodesChange])
|
||||
|
||||
const handleEdgesChange = useCallback((changes) => {
|
||||
onEdgesChange(changes)
|
||||
setHasUnsavedChanges(true)
|
||||
}, [onEdgesChange])
|
||||
|
||||
// Load available basis prompts for Analysis nodes
|
||||
useEffect(() => {
|
||||
@@ -80,12 +124,33 @@ export default function WorkflowEditorPage() {
|
||||
const { errors, warnings } = validateWorkflowGraph(nodes, edges)
|
||||
setValidationErrors(errors)
|
||||
setValidationWarnings(warnings)
|
||||
|
||||
// Re-show validation panel if there are new errors/warnings
|
||||
if (errors.length > 0 || warnings.length > 0) {
|
||||
setShowValidationPanel(true)
|
||||
}
|
||||
}, [nodes, edges])
|
||||
|
||||
// Warn on browser back/refresh if unsaved changes
|
||||
useEffect(() => {
|
||||
const handleBeforeUnload = (e) => {
|
||||
if (hasUnsavedChanges) {
|
||||
e.preventDefault()
|
||||
e.returnValue = '' // Chrome requires returnValue to be set
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener('beforeunload', handleBeforeUnload)
|
||||
return () => window.removeEventListener('beforeunload', handleBeforeUnload)
|
||||
}, [hasUnsavedChanges])
|
||||
|
||||
// ── Handlers ──────────────────────────────────────────────────────────────
|
||||
|
||||
const onConnect = useCallback(
|
||||
(params) => setEdges((eds) => addEdge(params, eds)),
|
||||
(params) => {
|
||||
setEdges((eds) => addEdge(params, eds))
|
||||
setHasUnsavedChanges(true)
|
||||
},
|
||||
[setEdges]
|
||||
)
|
||||
|
||||
@@ -94,16 +159,27 @@ export default function WorkflowEditorPage() {
|
||||
}, [])
|
||||
|
||||
const handleAddNode = (nodeType) => {
|
||||
const newNode = {
|
||||
const base = {
|
||||
id: `node_${nodeIdCounter++}`,
|
||||
type: nodeType,
|
||||
position: { x: 250, y: 100 + nodes.length * 100 },
|
||||
data: {
|
||||
label: `${nodeType.charAt(0).toUpperCase() + nodeType.slice(1)} ${nodeIdCounter - 1}`
|
||||
label: `${nodeType.charAt(0).toUpperCase() + nodeType.slice(1)} ${nodeIdCounter - 1}`,
|
||||
},
|
||||
}
|
||||
if (nodeType === 'start') {
|
||||
base.data = {
|
||||
label: 'Start',
|
||||
analysis_title:
|
||||
workflowName && workflowName !== 'Neuer Workflow'
|
||||
? workflowName
|
||||
: '',
|
||||
analysis_description: '',
|
||||
analysis_category: 'ganzheitlich',
|
||||
}
|
||||
}
|
||||
|
||||
setNodes((nds) => [...nds, newNode])
|
||||
setNodes((nds) => [...nds, base])
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const handleNodeUpdate = (nodeId, updates) => {
|
||||
@@ -113,6 +189,7 @@ export default function WorkflowEditorPage() {
|
||||
console.log('📝 Nodes after update:', updated.find(n => n.id === nodeId))
|
||||
return updated
|
||||
})
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const handleDeleteNode = () => {
|
||||
@@ -121,6 +198,7 @@ export default function WorkflowEditorPage() {
|
||||
setNodes((nds) => nds.filter((n) => n.id !== selectedNode.id))
|
||||
setEdges((eds) => eds.filter((e) => e.source !== selectedNode.id && e.target !== selectedNode.id))
|
||||
setSelectedNodeId(null)
|
||||
setHasUnsavedChanges(true)
|
||||
}
|
||||
|
||||
const handleSave = async () => {
|
||||
@@ -143,31 +221,43 @@ export default function WorkflowEditorPage() {
|
||||
})
|
||||
console.log('📊 Serialized graph_data:', graph_data)
|
||||
|
||||
const { display_name, description, category } = getWorkflowAnalysisPublishFields(
|
||||
nodes,
|
||||
workflowName
|
||||
)
|
||||
|
||||
if (currentPrompt) {
|
||||
// Update existing
|
||||
console.log('📝 Updating existing workflow:', currentPrompt.id)
|
||||
await api.updateUnifiedPrompt(currentPrompt.id, {
|
||||
type: 'workflow',
|
||||
name: workflowName,
|
||||
description: workflowDescription,
|
||||
display_name,
|
||||
description: description ?? undefined,
|
||||
category,
|
||||
graph_data
|
||||
})
|
||||
alert('Workflow gespeichert!')
|
||||
setToast({ message: '✅ Workflow gespeichert!', type: 'success' })
|
||||
} else {
|
||||
// Create new
|
||||
console.log('✨ Creating new workflow')
|
||||
const result = await api.createUnifiedPrompt({
|
||||
type: 'workflow',
|
||||
name: workflowName,
|
||||
description: workflowDescription,
|
||||
display_name,
|
||||
description: description ?? undefined,
|
||||
category,
|
||||
graph_data
|
||||
})
|
||||
console.log('✅ Workflow created:', result)
|
||||
setCurrentPrompt({ id: result.id, slug: result.slug, name: workflowName })
|
||||
alert('Workflow erstellt!')
|
||||
setToast({ message: '✅ Workflow erstellt!', type: 'success' })
|
||||
console.log('🚀 Navigating to:', `/workflow-editor/${result.id}`)
|
||||
navigate(`/workflow-editor/${result.id}`)
|
||||
}
|
||||
|
||||
// Clear unsaved changes flag after successful save
|
||||
setHasUnsavedChanges(false)
|
||||
} catch (e) {
|
||||
console.error('❌ handleSave error:', e)
|
||||
setError(e.message)
|
||||
@@ -194,11 +284,30 @@ export default function WorkflowEditorPage() {
|
||||
const { nodes: loadedNodes, edges: loadedEdges } = deserializeFromWorkflowGraph(prompt.graph_data)
|
||||
console.log('🎯 Deserialized:', { nodes: loadedNodes, edges: loadedEdges })
|
||||
|
||||
setNodes(loadedNodes)
|
||||
const mergedNodes = loadedNodes.map((n) => {
|
||||
if (n.type !== 'start') return n
|
||||
const hasStoredTitle = Object.prototype.hasOwnProperty.call(n.data || {}, 'analysis_title')
|
||||
return {
|
||||
...n,
|
||||
data: {
|
||||
label: n.data?.label || 'Start',
|
||||
...n.data,
|
||||
analysis_title: hasStoredTitle
|
||||
? n.data.analysis_title
|
||||
: (prompt.display_name || prompt.name || ''),
|
||||
analysis_description: Object.prototype.hasOwnProperty.call(n.data || {}, 'analysis_description')
|
||||
? n.data.analysis_description
|
||||
: (prompt.description || ''),
|
||||
analysis_category:
|
||||
(n.data?.analysis_category || prompt.category || 'ganzheitlich').toLowerCase(),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
setNodes(mergedNodes)
|
||||
setEdges(loadedEdges)
|
||||
setCurrentPrompt(prompt)
|
||||
setWorkflowName(prompt.name)
|
||||
setWorkflowDescription(prompt.description || '')
|
||||
|
||||
// nodeIdCounter aktualisieren
|
||||
const maxId = Math.max(
|
||||
@@ -207,6 +316,9 @@ export default function WorkflowEditorPage() {
|
||||
)
|
||||
nodeIdCounter = maxId + 1
|
||||
console.log('✅ Workflow loaded successfully, nodes:', loadedNodes.length, 'edges:', loadedEdges.length)
|
||||
|
||||
// Clear unsaved changes flag after successful load
|
||||
setHasUnsavedChanges(false)
|
||||
} catch (e) {
|
||||
console.error('❌ loadWorkflow error:', e)
|
||||
setError(e.message)
|
||||
@@ -228,15 +340,18 @@ export default function WorkflowEditorPage() {
|
||||
}
|
||||
|
||||
const handleNew = () => {
|
||||
if (confirm('Neuen Workflow erstellen? Ungespeicherte Änderungen gehen verloren.')) {
|
||||
setNodes([])
|
||||
setEdges([])
|
||||
setCurrentPrompt(null)
|
||||
setWorkflowName('Neuer Workflow')
|
||||
setWorkflowDescription('')
|
||||
setSelectedNodeId(null)
|
||||
navigate('/workflow-editor/new')
|
||||
if (hasUnsavedChanges) {
|
||||
if (!confirm('Neuen Workflow erstellen? Ungespeicherte Änderungen gehen verloren.')) {
|
||||
return
|
||||
}
|
||||
}
|
||||
setNodes([])
|
||||
setEdges([])
|
||||
setCurrentPrompt(null)
|
||||
setWorkflowName('Neuer Workflow')
|
||||
setSelectedNodeId(null)
|
||||
setHasUnsavedChanges(false)
|
||||
navigate('/workflow-editor/new')
|
||||
}
|
||||
|
||||
const handleDelete = async () => {
|
||||
@@ -261,31 +376,81 @@ export default function WorkflowEditorPage() {
|
||||
setExecutionResult(result)
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
if (hasUnsavedChanges) {
|
||||
const confirm = window.confirm(
|
||||
'Du hast ungespeicherte Änderungen.\n\n' +
|
||||
'Möchtest du wirklich zurück gehen? Alle Änderungen gehen verloren.'
|
||||
)
|
||||
if (!confirm) return
|
||||
}
|
||||
navigate('/admin/prompts')
|
||||
}
|
||||
|
||||
const handleValidationNodeClick = (nodeId) => {
|
||||
// Select the node to show its config panel
|
||||
setSelectedNodeId(nodeId)
|
||||
|
||||
// TODO: Optional - scroll to node in canvas
|
||||
// ReactFlow doesn't expose a direct scrollTo API, but we could use fitView
|
||||
// or manual DOM manipulation if needed
|
||||
}
|
||||
|
||||
const handlePlaceholderSelect = (placeholderString) => {
|
||||
if (!selectedNode || selectedNode.type !== 'end') return
|
||||
if (!selectedNode) return
|
||||
|
||||
const textarea = endNodeTextareaRef.current
|
||||
const currentTemplate = selectedNode.data.template || ''
|
||||
// Target bestimmen: End Node oder Inline Template
|
||||
if (placeholderPickerTarget === 'end' && selectedNode.type === 'end') {
|
||||
const textarea = endNodeTextareaRef.current
|
||||
const currentTemplate = selectedNode.data.template || ''
|
||||
|
||||
// Wenn Textarea Ref verfügbar, an Cursor-Position einfügen
|
||||
if (textarea) {
|
||||
const cursorPos = textarea.selectionStart || currentTemplate.length
|
||||
const before = currentTemplate.substring(0, cursorPos)
|
||||
const after = currentTemplate.substring(cursorPos)
|
||||
const newTemplate = before + placeholderString + after
|
||||
// Wenn Textarea Ref verfügbar, an Cursor-Position einfügen
|
||||
if (textarea) {
|
||||
const cursorPos = textarea.selectionStart || currentTemplate.length
|
||||
const before = currentTemplate.substring(0, cursorPos)
|
||||
const after = currentTemplate.substring(cursorPos)
|
||||
const newTemplate = before + placeholderString + after
|
||||
|
||||
handleNodeUpdate(selectedNode.id, { template: newTemplate })
|
||||
handleNodeUpdate(selectedNode.id, { template: newTemplate })
|
||||
|
||||
// Cursor nach eingefügtem Platzhalter positionieren
|
||||
setTimeout(() => {
|
||||
const newPos = cursorPos + placeholderString.length
|
||||
textarea.setSelectionRange(newPos, newPos)
|
||||
textarea.focus()
|
||||
}, 0)
|
||||
} else {
|
||||
// Fallback: Am Ende einfügen
|
||||
const newTemplate = currentTemplate + placeholderString
|
||||
handleNodeUpdate(selectedNode.id, { template: newTemplate })
|
||||
// Cursor nach eingefügtem Platzhalter positionieren
|
||||
setTimeout(() => {
|
||||
const newPos = cursorPos + placeholderString.length
|
||||
textarea.setSelectionRange(newPos, newPos)
|
||||
textarea.focus()
|
||||
}, 0)
|
||||
} else {
|
||||
// Fallback: Am Ende einfügen
|
||||
const newTemplate = currentTemplate + placeholderString
|
||||
handleNodeUpdate(selectedNode.id, { template: newTemplate })
|
||||
}
|
||||
}
|
||||
|
||||
// Inline Template (Analysis Node)
|
||||
else if (placeholderPickerTarget === 'inline' && selectedNode.type === 'analysis') {
|
||||
const textarea = inlineTemplateTextareaRef.current
|
||||
const currentTemplate = selectedNode.data.inline_template || ''
|
||||
|
||||
// Wenn Textarea Ref verfügbar, an Cursor-Position einfügen
|
||||
if (textarea) {
|
||||
const cursorPos = textarea.selectionStart || currentTemplate.length
|
||||
const before = currentTemplate.substring(0, cursorPos)
|
||||
const after = currentTemplate.substring(cursorPos)
|
||||
const newTemplate = before + placeholderString + after
|
||||
|
||||
handleNodeUpdate(selectedNode.id, { inline_template: newTemplate })
|
||||
|
||||
// Cursor nach eingefügtem Platzhalter positionieren
|
||||
setTimeout(() => {
|
||||
const newPos = cursorPos + placeholderString.length
|
||||
textarea.setSelectionRange(newPos, newPos)
|
||||
textarea.focus()
|
||||
}, 0)
|
||||
} else {
|
||||
// Fallback: Am Ende einfügen
|
||||
const newTemplate = currentTemplate + placeholderString
|
||||
handleNodeUpdate(selectedNode.id, { inline_template: newTemplate })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -295,15 +460,19 @@ export default function WorkflowEditorPage() {
|
||||
<div className="workflow-editor">
|
||||
{/* Toolbar */}
|
||||
<div className="workflow-toolbar">
|
||||
<button className="btn-secondary" onClick={() => navigate('/admin/prompts')}>
|
||||
<button className="btn-secondary" onClick={handleBack}>
|
||||
← Zurück
|
||||
</button>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
value={workflowName}
|
||||
onChange={(e) => setWorkflowName(e.target.value)}
|
||||
placeholder="Workflow-Name"
|
||||
onChange={(e) => {
|
||||
setWorkflowName(e.target.value)
|
||||
setHasUnsavedChanges(true)
|
||||
}}
|
||||
placeholder="Interner Workflow-Name (Slug-Basis)"
|
||||
title="Technischer Name in der Datenbank. Den sichtbaren Titel für die KI-Analyse setzt du in der Start-Node."
|
||||
style={{ flex: 1, padding: '8px', borderRadius: '4px', border: '1px solid var(--border)' }}
|
||||
/>
|
||||
|
||||
@@ -400,8 +569,8 @@ export default function WorkflowEditorPage() {
|
||||
nodes={nodes}
|
||||
edges={edges}
|
||||
nodeTypes={nodeTypes}
|
||||
onNodesChange={onNodesChange}
|
||||
onEdgesChange={onEdgesChange}
|
||||
onNodesChange={handleNodesChange}
|
||||
onEdgesChange={handleEdgesChange}
|
||||
onConnect={onConnect}
|
||||
onNodeClick={onNodeClick}
|
||||
/>
|
||||
@@ -429,9 +598,115 @@ export default function WorkflowEditorPage() {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Inline Validation Display */}
|
||||
{(validationErrors.length > 0 || validationWarnings.length > 0) && (
|
||||
<div style={{
|
||||
background: validationErrors.length > 0 ? '#ffebee' : '#fff3cd',
|
||||
border: `1px solid ${validationErrors.length > 0 ? 'var(--danger)' : '#FFC107'}`,
|
||||
borderRadius: '8px',
|
||||
padding: '12px',
|
||||
marginBottom: '16px'
|
||||
}}>
|
||||
<div style={{ fontWeight: 600, marginBottom: '8px', color: validationErrors.length > 0 ? 'var(--danger)' : '#856404' }}>
|
||||
{validationErrors.length > 0 ? `❌ ${validationErrors.length} Fehler` : `⚠️ ${validationWarnings.length} Warnungen`}
|
||||
</div>
|
||||
{validationErrors.map((err, i) => (
|
||||
<div key={`err-${i}`} style={{ fontSize: '13px', marginBottom: '4px', color: 'var(--danger)', cursor: err.nodeId ? 'pointer' : 'default' }}
|
||||
onClick={() => err.nodeId && setSelectedNodeId(err.nodeId)}>
|
||||
• {err.message}
|
||||
</div>
|
||||
))}
|
||||
{validationWarnings.map((warn, i) => (
|
||||
<div key={`warn-${i}`} style={{ fontSize: '13px', marginBottom: '4px', color: '#856404', cursor: warn.nodeId ? 'pointer' : 'default' }}
|
||||
onClick={() => warn.nodeId && setSelectedNodeId(warn.nodeId)}>
|
||||
• {warn.message}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Start-Node: Metadaten für KI-Analyse (wie Pipeline: display_name, description, category) */}
|
||||
{selectedNode.type === 'start' && (
|
||||
<div className="config-section" style={{ marginBottom: 20 }}>
|
||||
<h3 style={{ margin: '0 0 10px', fontSize: 15 }}>Anzeige in KI-Analyse</h3>
|
||||
<p style={{ fontSize: 12, color: 'var(--text3)', lineHeight: 1.5, marginBottom: 12 }}>
|
||||
Titel, Kurzbeschreibung und Kategorie erscheinen auf der Analyse-Seite, im Verlauf und in der
|
||||
Kategorie-Navigation – analog zu Pipeline-Prompts im Admin.
|
||||
</p>
|
||||
<label style={{ display: 'block', marginBottom: 6, fontWeight: 600, fontSize: 13 }}>
|
||||
Titel (sichtbar für Nutzer)
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={selectedNode.data.analysis_title ?? ''}
|
||||
onChange={(e) =>
|
||||
handleNodeUpdate(selectedNode.id, { analysis_title: e.target.value })
|
||||
}
|
||||
placeholder="z. B. Ganzheitliche Auswertung"
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
color: 'var(--text1)',
|
||||
fontSize: '14px',
|
||||
marginBottom: 12,
|
||||
}}
|
||||
/>
|
||||
<label style={{ display: 'block', marginBottom: 6, fontWeight: 600, fontSize: 13 }}>
|
||||
Kurzbeschreibung (optional)
|
||||
</label>
|
||||
<textarea
|
||||
value={selectedNode.data.analysis_description ?? ''}
|
||||
onChange={(e) =>
|
||||
handleNodeUpdate(selectedNode.id, { analysis_description: e.target.value })
|
||||
}
|
||||
placeholder="Ein Satz, worum es bei dieser Auswertung geht …"
|
||||
rows={4}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
color: 'var(--text1)',
|
||||
fontSize: '13px',
|
||||
lineHeight: 1.5,
|
||||
marginBottom: 12,
|
||||
resize: 'vertical',
|
||||
}}
|
||||
/>
|
||||
<label style={{ display: 'block', marginBottom: 6, fontWeight: 600, fontSize: 13 }}>
|
||||
Kategorie
|
||||
</label>
|
||||
<select
|
||||
value={selectedNode.data.analysis_category || 'ganzheitlich'}
|
||||
onChange={(e) =>
|
||||
handleNodeUpdate(selectedNode.id, { analysis_category: e.target.value })
|
||||
}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
color: 'var(--text1)',
|
||||
fontSize: '14px',
|
||||
}}
|
||||
>
|
||||
{ANALYSIS_CATEGORY_ORDER.map((key) => (
|
||||
<option key={key} value={key}>
|
||||
{ANALYSIS_CATEGORY_LABELS[key] || key}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Basis-Konfiguration */}
|
||||
<div className="config-section">
|
||||
<label>Node-Name</label>
|
||||
<label>Node-Name {selectedNode.type === 'start' && '(auf dem Canvas)'}</label>
|
||||
<input
|
||||
type="text"
|
||||
value={selectedNode.data.label || ''}
|
||||
@@ -453,49 +728,112 @@ export default function WorkflowEditorPage() {
|
||||
</div>
|
||||
|
||||
{/* Type-spezifische Konfiguration */}
|
||||
{selectedNode.type === 'analysis' && (
|
||||
<>
|
||||
<div className="config-section">
|
||||
<label>KI-Prompt auswählen</label>
|
||||
<select
|
||||
value={selectedNode.data.prompt_slug ? String(selectedNode.data.prompt_slug) : ''}
|
||||
onChange={(e) => {
|
||||
const promptSlug = e.target.value
|
||||
console.log('🎯 Prompt selected:', promptSlug, 'Type:', typeof promptSlug)
|
||||
const selectedPrompt = availablePrompts.find(p => p.slug === promptSlug)
|
||||
console.log('📋 Selected prompt object:', selectedPrompt)
|
||||
handleNodeUpdate(selectedNode.id, {
|
||||
prompt_slug: promptSlug || null,
|
||||
prompt_name: selectedPrompt?.name || null
|
||||
})
|
||||
}}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
color: 'var(--text1)'
|
||||
}}
|
||||
>
|
||||
<option value="">-- Basis-Prompt wählen --</option>
|
||||
{availablePrompts.map(prompt => (
|
||||
<option key={prompt.id} value={prompt.slug}>
|
||||
{prompt.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedNode.data.prompt_slug && (
|
||||
<div style={{ marginTop: 8, fontSize: 12, color: 'var(--text3)' }}>
|
||||
Prompt: {selectedNode.data.prompt_slug} ({selectedNode.data.prompt_name || 'unbekannt'})
|
||||
{selectedNode.type === 'analysis' && (() => {
|
||||
// Helper: Bestimme aktuellen Mode basierend auf node.data
|
||||
const isInlineMode = selectedNode.data.inline_template !== null && selectedNode.data.inline_template !== undefined
|
||||
const isReferenceMode = !isInlineMode
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Prompt Source Selector */}
|
||||
<div className="config-section">
|
||||
<label className="form-label">Prompt-Quelle</label>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
|
||||
<label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="radio"
|
||||
name={`promptSource-${selectedNode.id}`}
|
||||
checked={isReferenceMode}
|
||||
onChange={() => {
|
||||
// Wechsel zu Reference Mode
|
||||
handleNodeUpdate(selectedNode.id, {
|
||||
inline_template: null, // Inline löschen
|
||||
prompt_slug: selectedNode.data.prompt_slug || '' // Behalte existierenden slug
|
||||
})
|
||||
}}
|
||||
style={{ marginRight: '8px' }}
|
||||
/>
|
||||
<span style={{ fontSize: '14px' }}>📚 Basis-Prompt referenzieren</span>
|
||||
</label>
|
||||
<label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
|
||||
<input
|
||||
type="radio"
|
||||
name={`promptSource-${selectedNode.id}`}
|
||||
checked={isInlineMode}
|
||||
onChange={() => {
|
||||
// Wechsel zu Inline Mode
|
||||
// WICHTIG: prompt_slug NICHT löschen, damit er beim Zurückwechseln noch da ist
|
||||
handleNodeUpdate(selectedNode.id, {
|
||||
inline_template: selectedNode.data.inline_template || '' // Aktiviere Inline Mode
|
||||
})
|
||||
}}
|
||||
style={{ marginRight: '8px' }}
|
||||
/>
|
||||
<span style={{ fontSize: '14px' }}>✏️ Inline-Template erstellen</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Conditional Rendering: Reference Mode */}
|
||||
{isReferenceMode && (
|
||||
<div className="config-section">
|
||||
<label>Basis-Prompt auswählen</label>
|
||||
<select
|
||||
value={selectedNode.data.prompt_slug || ''}
|
||||
onChange={(e) => {
|
||||
const promptSlug = e.target.value
|
||||
const selectedPrompt = availablePrompts.find(p => p.slug === promptSlug)
|
||||
handleNodeUpdate(selectedNode.id, {
|
||||
prompt_slug: promptSlug,
|
||||
prompt_name: selectedPrompt?.name || null,
|
||||
inline_template: null
|
||||
})
|
||||
}}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '8px',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid var(--border)',
|
||||
background: 'var(--surface)',
|
||||
color: 'var(--text1)'
|
||||
}}
|
||||
>
|
||||
<option value="">-- Basis-Prompt wählen --</option>
|
||||
{availablePrompts.map(prompt => (
|
||||
<option key={prompt.id} value={prompt.slug}>
|
||||
{prompt.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{selectedNode.data.prompt_slug && (
|
||||
<div style={{ marginTop: 8, fontSize: 12, color: 'var(--text3)' }}>
|
||||
Prompt: {selectedNode.data.prompt_slug} ({selectedNode.data.prompt_name || 'unbekannt'})
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<QuestionAugmentationPanel node={selectedNode} onChange={handleNodeUpdate} />
|
||||
<FallbackConfig node={selectedNode} edges={edges} nodes={nodes} onChange={handleNodeUpdate} />
|
||||
</>
|
||||
)}
|
||||
{/* Conditional Rendering: Inline Mode */}
|
||||
{isInlineMode && (
|
||||
<InlineTemplateEditor
|
||||
value={selectedNode.data.inline_template || ''}
|
||||
onChange={(template) => handleNodeUpdate(selectedNode.id, {
|
||||
inline_template: template,
|
||||
prompt_slug: null
|
||||
})}
|
||||
onPlaceholderPick={() => {
|
||||
setPlaceholderPickerTarget('inline')
|
||||
setShowPlaceholderPicker(true)
|
||||
}}
|
||||
textareaRef={inlineTemplateTextareaRef}
|
||||
/>
|
||||
)}
|
||||
|
||||
<QuestionAugmentationPanel node={selectedNode} onChange={handleNodeUpdate} />
|
||||
<FallbackConfig node={selectedNode} edges={edges} nodes={nodes} onChange={handleNodeUpdate} />
|
||||
</>
|
||||
)
|
||||
})()}
|
||||
|
||||
{selectedNode.type === 'logic' && (
|
||||
<>
|
||||
@@ -517,7 +855,10 @@ export default function WorkflowEditorPage() {
|
||||
<EndNodeConfig
|
||||
node={selectedNode}
|
||||
onChange={handleNodeUpdate}
|
||||
onOpenPlaceholderPicker={() => setShowPlaceholderPicker(true)}
|
||||
onOpenPlaceholderPicker={() => {
|
||||
setPlaceholderPickerTarget('end')
|
||||
setShowPlaceholderPicker(true)
|
||||
}}
|
||||
textareaRef={endNodeTextareaRef}
|
||||
/>
|
||||
)}
|
||||
@@ -525,36 +866,7 @@ export default function WorkflowEditorPage() {
|
||||
)}
|
||||
</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) {
|
||||
setSelectedNodeId(err.nodeId)
|
||||
}
|
||||
}}>
|
||||
❌ {err.message}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{validationWarnings.map((warn, i) => (
|
||||
<div key={i} className="validation-warning" onClick={() => {
|
||||
if (warn.nodeId) {
|
||||
setSelectedNodeId(warn.nodeId)
|
||||
}
|
||||
}}>
|
||||
⚠️ {warn.message}
|
||||
</div>
|
||||
))}
|
||||
|
||||
{validationErrors.length === 0 && validationWarnings.length > 0 && (
|
||||
<div className="validation-success">
|
||||
✅ Workflow ist valide ({validationWarnings.length} Warnungen)
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* Validation Panel - REMOVED (moved to config panel header) */}
|
||||
|
||||
{/* Execution Result Viewer */}
|
||||
{executionResult && (
|
||||
@@ -568,10 +880,43 @@ export default function WorkflowEditorPage() {
|
||||
{showPlaceholderPicker && (
|
||||
<PlaceholderPicker
|
||||
nodes={nodes}
|
||||
currentNodeId={selectedNode?.id}
|
||||
onSelect={handlePlaceholderSelect}
|
||||
onClose={() => setShowPlaceholderPicker(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Validation Panel */}
|
||||
{showValidationPanel && (validationErrors.length > 0 || validationWarnings.length > 0) && (
|
||||
<ValidationPanel
|
||||
errors={validationErrors}
|
||||
warnings={validationWarnings}
|
||||
onNodeClick={handleValidationNodeClick}
|
||||
onClose={() => setShowValidationPanel(false)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Toast Notification */}
|
||||
{toast && (
|
||||
<Toast
|
||||
message={toast.message}
|
||||
type={toast.type}
|
||||
duration={toast.duration || 3000}
|
||||
onClose={() => setToast(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Confirm Dialog */}
|
||||
{confirmDialog && (
|
||||
<ConfirmDialog
|
||||
message={confirmDialog.message}
|
||||
onConfirm={confirmDialog.onConfirm}
|
||||
onCancel={() => setConfirmDialog(null)}
|
||||
confirmText={confirmDialog.confirmText}
|
||||
cancelText={confirmDialog.cancelText}
|
||||
type={confirmDialog.type}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -27,7 +27,7 @@
|
||||
/* ── Sidebar (Node Palette) ─────────────────────────────────────────────── */
|
||||
|
||||
.workflow-sidebar {
|
||||
width: 250px;
|
||||
width: 220px;
|
||||
background: var(--surface);
|
||||
border-right: 1px solid var(--border);
|
||||
padding: 16px;
|
||||
@@ -268,7 +268,7 @@
|
||||
/* ── Config Panel ────────────────────────────────────────────────────────── */
|
||||
|
||||
.workflow-config-panel {
|
||||
width: 400px;
|
||||
width: 520px;
|
||||
background: var(--surface);
|
||||
border-left: 1px solid var(--border);
|
||||
padding: 16px;
|
||||
@@ -453,7 +453,7 @@
|
||||
}
|
||||
|
||||
.workflow-config-panel {
|
||||
width: 350px;
|
||||
width: 450px;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Nutzer-sichtbare Textausgabe eines Workflow-Laufs – gleiche Logik wie
|
||||
* WorkflowResultViewer („Final Output“): primär aggregated_result.analysis_core.
|
||||
*/
|
||||
const AGG_META_KEYS = new Set([
|
||||
'combined_analysis',
|
||||
'all_signals',
|
||||
'total_nodes',
|
||||
'executed_nodes',
|
||||
'failed_nodes',
|
||||
'skipped_nodes',
|
||||
])
|
||||
|
||||
export function getWorkflowDisplayContent(aggregatedResult) {
|
||||
if (aggregatedResult == null) return ''
|
||||
if (typeof aggregatedResult !== 'object' || Array.isArray(aggregatedResult)) {
|
||||
return typeof aggregatedResult === 'string'
|
||||
? aggregatedResult
|
||||
: JSON.stringify(aggregatedResult, null, 2)
|
||||
}
|
||||
|
||||
const core = aggregatedResult.analysis_core
|
||||
if (typeof core === 'string' && core.trim() !== '') return core
|
||||
|
||||
const combined = aggregatedResult.combined_analysis
|
||||
if (typeof combined === 'string' && combined.trim() !== '') return combined
|
||||
|
||||
const keys = Object.keys(aggregatedResult).filter((k) => !AGG_META_KEYS.has(k))
|
||||
if (keys.length === 1) {
|
||||
const v = aggregatedResult[keys[0]]
|
||||
if (typeof v === 'string') return v
|
||||
if (v != null && typeof v === 'object') return JSON.stringify(v, null, 2)
|
||||
return String(v)
|
||||
}
|
||||
|
||||
return JSON.stringify(aggregatedResult, null, 2)
|
||||
}
|
||||
@@ -22,6 +22,7 @@ export function serializeToWorkflowGraph(nodes, edges, metadata = {}) {
|
||||
// Type-spezifische Felder
|
||||
...(node.type === 'analysis' && {
|
||||
prompt_slug: node.data.prompt_slug || null,
|
||||
inline_template: node.data.inline_template || null, // Part 3: Inline Prompts
|
||||
prompt_name: node.data.prompt_name || null,
|
||||
question_augmentations: node.data.questions || [], // Backend erwartet question_augmentations
|
||||
fallback_strategy: node.data.fallback_strategy || 'conservative_skip'
|
||||
@@ -41,6 +42,12 @@ export function serializeToWorkflowGraph(nodes, edges, metadata = {}) {
|
||||
...(node.type === 'end' && {
|
||||
output_mode: node.data.output_mode || 'auto',
|
||||
template: node.data.template || null
|
||||
}),
|
||||
|
||||
...(node.type === 'start' && {
|
||||
analysis_title: node.data.analysis_title || '',
|
||||
analysis_description: node.data.analysis_description || '',
|
||||
analysis_category: node.data.analysis_category || 'ganzheitlich',
|
||||
})
|
||||
}))
|
||||
|
||||
@@ -84,6 +91,7 @@ export function deserializeFromWorkflowGraph(jsonbData) {
|
||||
|
||||
...(node.type === 'analysis' && {
|
||||
prompt_slug: node.prompt_slug || node.prompt_id || null, // Fallback für alte Workflows mit prompt_id
|
||||
inline_template: node.inline_template || null, // Part 3: Inline Prompts
|
||||
prompt_name: node.prompt_name || null, // Falls vom Backend mitgeliefert
|
||||
questions: node.question_augmentations || node.questions || [], // Backend sendet question_augmentations
|
||||
fallback_strategy: node.fallback_strategy || 'conservative_skip'
|
||||
@@ -103,6 +111,12 @@ export function deserializeFromWorkflowGraph(jsonbData) {
|
||||
...(node.type === 'end' && {
|
||||
output_mode: node.output_mode || 'auto',
|
||||
template: node.template || null
|
||||
}),
|
||||
|
||||
...(node.type === 'start' && {
|
||||
analysis_title: node.analysis_title || '',
|
||||
analysis_description: node.analysis_description || '',
|
||||
analysis_category: node.analysis_category || 'ganzheitlich',
|
||||
})
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -49,6 +49,14 @@ function validateStructure(nodes, edges, errors, warnings) {
|
||||
message: 'Kein END-Node vorhanden',
|
||||
severity: 'error'
|
||||
})
|
||||
} else if (endNodes.length > 1) {
|
||||
// Backend unterstützt aktuell nur 1 End-Node (aggregate_results nimmt letzten)
|
||||
// Future: Multi-Exit Support würde Backend-Anpassung erfordern
|
||||
errors.push({
|
||||
type: 'structure',
|
||||
message: `${endNodes.length} END-Nodes gefunden (max. 1 erlaubt)`,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
// Zyklen-Erkennung
|
||||
@@ -86,17 +94,29 @@ function validateLogic(nodes, edges, errors, warnings) {
|
||||
// Analysis Nodes
|
||||
if (node.type === 'analysis') {
|
||||
const questions = node.data.questions || []
|
||||
const hasPromptSlug = node.data.prompt_slug != null && node.data.prompt_slug !== ''
|
||||
const hasInlineTemplate = node.data.inline_template != null && node.data.inline_template.trim() !== ''
|
||||
|
||||
// Prompt ausgewählt?
|
||||
if (!node.data.prompt_slug) {
|
||||
// Part 3: Validation - Entweder prompt_slug ODER inline_template
|
||||
if (!hasPromptSlug && !hasInlineTemplate) {
|
||||
errors.push({
|
||||
type: 'config',
|
||||
message: `Analysis-Node "${node.data.label}" hat keinen Prompt`,
|
||||
message: `Analysis-Node "${node.data.label}" benötigt entweder Basis-Prompt oder Inline-Template`,
|
||||
nodeId: node.id,
|
||||
severity: 'error'
|
||||
})
|
||||
}
|
||||
|
||||
// Warning wenn beide gesetzt (sollte nicht passieren, aber zur Sicherheit)
|
||||
if (hasPromptSlug && hasInlineTemplate) {
|
||||
warnings.push({
|
||||
type: 'config',
|
||||
message: `Analysis-Node "${node.data.label}" hat sowohl Basis-Prompt als auch Inline-Template - Inline hat Vorrang`,
|
||||
nodeId: node.id,
|
||||
severity: 'warning'
|
||||
})
|
||||
}
|
||||
|
||||
// Fragen validieren
|
||||
questions.forEach((q, idx) => {
|
||||
if (!q.question?.trim()) {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test placeholder resolution in inline templates
|
||||
|
||||
This script simulates what happens in workflow_executor.load_prompt_template()
|
||||
"""
|
||||
import sys
|
||||
sys.path.insert(0, 'backend')
|
||||
|
||||
from placeholder_resolver import get_placeholder_example_values, get_placeholder_catalog
|
||||
from prompt_executor import resolve_placeholders
|
||||
|
||||
# Test profile_id (use first profile in dev DB)
|
||||
PROFILE_ID = "019601b5-d65a-738f-a1e7-b3f69bb97f69" # Lars profile from dev
|
||||
|
||||
def test_placeholder_resolution():
|
||||
"""Test the exact same logic as in workflow_executor.load_prompt_template()"""
|
||||
|
||||
# Test template with spaces in placeholders (as user showed)
|
||||
template = "Hallo {{ name }}, du bist {{ age }} Jahre alt und {{ geschlecht }}."
|
||||
|
||||
print("=" * 80)
|
||||
print("PLACEHOLDER RESOLUTION TEST")
|
||||
print("=" * 80)
|
||||
print(f"\nTemplate:\n{template}\n")
|
||||
|
||||
# Step 1: Load placeholders (same as workflow_executor)
|
||||
print("Step 1: Loading placeholders...")
|
||||
processed_placeholders = get_placeholder_example_values(PROFILE_ID)
|
||||
print(f" Loaded {len(processed_placeholders)} placeholders")
|
||||
print(f" Sample keys (first 5): {list(processed_placeholders.keys())[:5]}")
|
||||
|
||||
# Step 2: Clean keys (same as workflow_executor)
|
||||
print("\nStep 2: Cleaning keys...")
|
||||
cleaned_placeholders = {
|
||||
key.replace('{{', '').replace('}}', '').strip(): value
|
||||
for key, value in processed_placeholders.items()
|
||||
}
|
||||
print(f" Cleaned keys (first 5): {list(cleaned_placeholders.keys())[:5]}")
|
||||
print(f" Sample values:")
|
||||
print(f" name = {cleaned_placeholders.get('name')}")
|
||||
print(f" age = {cleaned_placeholders.get('age')}")
|
||||
print(f" geschlecht = {cleaned_placeholders.get('geschlecht')}")
|
||||
|
||||
variables = cleaned_placeholders
|
||||
|
||||
# Step 3: Load catalog
|
||||
print("\nStep 3: Loading catalog...")
|
||||
try:
|
||||
catalog = get_placeholder_catalog(PROFILE_ID)
|
||||
print(f" Catalog loaded with {len(catalog)} categories")
|
||||
except Exception as e:
|
||||
catalog = None
|
||||
print(f" Catalog failed: {e}")
|
||||
|
||||
# Step 4: Resolve placeholders
|
||||
print("\nStep 4: Resolving placeholders...")
|
||||
debug_info = {}
|
||||
resolved = resolve_placeholders(
|
||||
template=template,
|
||||
variables=variables,
|
||||
debug_info=debug_info,
|
||||
catalog=catalog
|
||||
)
|
||||
|
||||
print(f" Resolved placeholders: {debug_info.get('resolved_placeholders', {})}")
|
||||
print(f" Unresolved placeholders: {debug_info.get('unresolved_placeholders', [])}")
|
||||
|
||||
# Result
|
||||
print("\n" + "=" * 80)
|
||||
print("RESULT")
|
||||
print("=" * 80)
|
||||
print(f"\nResolved template:\n{resolved}\n")
|
||||
|
||||
# Check if placeholders were resolved
|
||||
if '{{' in resolved:
|
||||
print("❌ FAILED: Some placeholders were not resolved!")
|
||||
return False
|
||||
else:
|
||||
print("✅ SUCCESS: All placeholders resolved!")
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_placeholder_resolution()
|
||||
sys.exit(0 if success else 1)
|
||||
Reference in new issue
Block a user