feat: Add KI-Einstiegsscript for comprehensive project overview

- Introduced `ki_project_overview.py` for automated analysis of EspoCRM project structure, entities, relationships, custom PHP classes, workflows, frontend adjustments, and internationalization.
- Created `ki-overview.sh` wrapper script for executing the Python script with various output options.
- Updated `README.md` to include a quick start section for the new KI entry script.
- Added detailed documentation in `KI_OVERVIEW_README.md` explaining the script's purpose, usage, and output format.
- Summarized the new features and files in `KI_OVERVIEW_SUMMARY.md`.
- Enhanced `.vscode/settings.json` to approve new scripts for execution.
This commit is contained in:
2026-01-25 12:34:46 +01:00
parent b8147f6e61
commit 552540e214
6 changed files with 1185 additions and 52 deletions

View File

@@ -32,6 +32,11 @@
"/^python3 /var/lib/docker/volumes/vmh-espocrm_espocrm/_data/custom/scripts/validate_and_rebuild\\.py$/": {
"approve": true,
"matchCommandLine": true
}
},
"/^python3 custom/scripts/project_overview\\.py$/": {
"approve": true,
"matchCommandLine": true
},
"./custom/scripts/ki-overview.sh": true
}
}

View File

@@ -1,5 +1,22 @@
KI-basierte Bearbeitung von EspoCRM: Struktur und Funktionsweise
## 🚀 Schnellstart für KI
**NEU:** Automatisches KI-Einstiegsscript für vollständigen Projekt-Überblick!
```bash
# Vollständige Projekt-Analyse für KI
./custom/scripts/ki-overview.sh
# Nur Schnellübersicht
./custom/scripts/ki-overview.sh --stats
# In Datei speichern
./custom/scripts/ki-overview.sh --file /tmp/overview.txt
```
Das Script analysiert automatisch alle Entitäten, Beziehungen, Custom Code, Workflows und Frontend-Anpassungen. Siehe [KI_OVERVIEW_README.md](custom/scripts/KI_OVERVIEW_README.md) für Details.
## Inhaltsverzeichnis
1. [Überblick](#überblick)
2. [Custom Directory Struktur](#custom-directory-struktur)
@@ -48,9 +65,7 @@ Keine integrierte KI-Schnittstelle existiert, aber mit Dateizugriff können auto
**Zentrales Tool:** `custom/scripts/validate_and_rebuild.py`
**NEU ab Januar 2026:** Erweitertes Python-basiertes Validierungs-Tool mit automatischen Checks!
Dieses Script sollte **IMMER** verwendet werden (nicht manueller Rebuild). Es führt automatisch aus:
Dieses Script sollte **IMMER** verwendet werden (niemals manueller Rebuild). Es führt automatisch aus:
**Validierungen:**
- JSON-Syntax-Prüfung aller `.json` Dateien im `custom/` Verzeichnis
@@ -1356,28 +1371,6 @@ docker exec espocrm php /var/www/html/custom/scripts/workflow_manager.php import
/var/www/html/custom/workflows/vmh-erstberatung-abschliessen.json
```
### Workflow-Entwicklung mit KI
Für KI-gestützte Workflow-Erstellung:
1. Workflow-Definition im `custom/workflows/` Verzeichnis als JSON ablegen
2. Mit `import` Befehl in EspoCRM einspielen
3. Im Admin-Interface testen und bei Bedarf anpassen
4. Mit `export` Befehl aktualisierten Workflow sichern
5. JSON-Datei im Repository committen
## Projektziele und Zukunftsvision: "Vermieterhelden"
Das Projekt "Vermieterhelden" ist ein maßgeschneidertes Backend-System auf Basis von EspoCRM für eine Anwaltskanzlei, spezialisiert auf die Durchführung und Verwaltung von immobilienrechtlichen Klagen (z. B. Räumungsklagen, Mietinkasso). Der aktuelle Fokus liegt auf der strukturierten Verwaltung von Stammdaten (Entitäten wie Mietverhältnisse, Mietobjekte, Beteiligte, Dokumente und Klagen) und der Abbildung von rechtlichen Workflows (z. B. automatisierte Tasks bei Statusänderungen, Fristen-Überwachung).
Zukünftige Ziele:
- **Customer Portal**: Integration eines Mandanten-Portals, damit Klienten (Mieter/Vermieter) selbst auf relevante Daten zugreifen können (z. B. Status von Klagen, Dokumente hochladen). Dies nutzt EspoCRMs eingebaute Portal-Funktionalität für Self-Service.
- **KI-Integration über Middleware**: Automatisierung von Prozessen via Webhooks und externer Middleware. Beispiele:
- Automatische Analyse von Dokumenten (z. B. Verträge scannen und Felder extrahieren).
- Intelligente Fristen-Erinnerungen basierend auf rechtlichen Regeln (z. B. Kündigungsfristen berechnen).
- Workflow-Optimierung (z. B. Vorschläge für nächste Schritte in Klage-Prozessen).
- Die KI soll über APIs/Webhooks angebunden werden, ohne EspoCRMs Core zu modifizieren, um Stabilität zu wahren.
- **Erweiterte Features**: Mehrsprachigkeit, Mandanten-Isolation für mehrere Kanzlei-Teams, Integration mit externen Systemen (z. B. Gerichts-APIs, Buchhaltung).
Die KI kann diese Ziele unterstützen, indem sie JSON-Strukturen analysiert, Änderungen vorschlägt (z. B. neue Felder für Compliance) und Workflows modelliert. Das System soll skalierbar und benutzerfreundlich sein, um die Effizienz in der Rechtsbranche zu steigern.
6. Bearbeitung von Entitäten und Layouts
@@ -1482,32 +1475,6 @@ Um Relationship-Panels und Links korrekt zu beschriften, müssen Labels in den i
- Bei Relationship-Problemen: Logs nach "404" und "Link does not exist" durchsuchen: `tail -n 500 /var/lib/docker/volumes/vmh-espocrm_espocrm/_data/data/logs/espo-$(date +%Y-%m-%d).log | grep -A 3 "404\|Link does not exist"`
- Bei DB-Problemen: Custom-Scripts wie `workflow_manager.php` verwenden.
### Check & Rebuild Script
Das Script `custom/scripts/check_and_rebuild.sh` automatisiert die Qualitätssicherung und führt folgende Prüfungen durch:
1. **JSON-Syntax-Validierung**: Prüft alle `.json` Dateien im `custom/` Verzeichnis auf gültiges JSON
2. **Dateirechte-Prüfung**: Stellt sicher, dass alle Dateien `www-data:www-data` als Owner haben
3. **System-Checks**: Validiert Existenz von Cache- und Logs-Verzeichnissen
4. **Automatischer Rebuild**: Bei Fehlerfreiheit wird der Rebuild durchgeführt
**Verwendung:**
```bash
# Im EspoCRM-Root-Verzeichnis ausführen
./custom/scripts/check_and_rebuild.sh
```
**Ausgabe:**
- ✓ Grün: Alles in Ordnung
- ⚠ Gelb: Warnungen (Rebuild wird trotzdem ausgeführt)
- ✗ Rot: Fehler (Rebuild wird NICHT ausgeführt)
**Bei Berechtigungsfehlern:**
```bash
sudo chown -R www-data:www-data custom/
sudo find custom/ -type f -name "*.json" -exec chmod 664 {} \;
sudo find custom/ -type d -exec chmod 775 {} \;
```
## 9. Reports und Report-Panels

View File

@@ -0,0 +1,334 @@
# KI-Einstiegsscript für EspoCRM Projekt
## Übersicht
Das `ki_project_overview.py` Script bietet einen vollständigen, automatisch generierten Überblick über das EspoCRM-Projekt. Es ist speziell für KI-basierte Programmierung konzipiert und gibt alle relevanten Informationen aus, die für die Entwicklung benötigt werden.
## Zweck
**Ziel:** Die KI erhält einen aktuellen, umfassenden Informationsstand über das Projekt, ohne manuell verschiedene Dateien durchsuchen zu müssen.
Das Script analysiert automatisch:
- ✅ Alle Custom Entitäten und ihre Felder
- ✅ Beziehungen zwischen Entitäten (Relationship-Graph)
- ✅ Custom PHP Klassen (Formula-Funktionen, Services, etc.)
- ✅ Workflows und deren Status
- ✅ Frontend-Anpassungen (JavaScript, CSS)
- ✅ Custom Layouts
- ✅ Internationalisierung (i18n)
- ✅ README.md Dokumentation
## Verwendung
### Einfach ausführen
```bash
# Im EspoCRM Root-Verzeichnis
python3 custom/scripts/ki_project_overview.py
```
### Ausgabe in Datei speichern
```bash
# Für detaillierte Analyse später
python3 custom/scripts/ki_project_overview.py > /tmp/project-overview.txt
```
### Ausgabe an KI übergeben
Das Script ist so konzipiert, dass die Ausgabe direkt an eine KI übergeben werden kann. Die KI erhält damit:
1. **Schnellübersicht** - Projekt-Statistiken auf einen Blick
2. **README.md** - Vollständige Projektdokumentation
3. **Entitäten-Analyse** - Alle Custom Entities mit Feldern und Beziehungen
4. **Beziehungsgraph** - Wie Entitäten miteinander verbunden sind
5. **Custom Code** - PHP Klassen, JavaScript, CSS
6. **Workflows** - Aktive und inaktive Workflows
7. **Internationalisierung** - Unterstützte Sprachen
## Ausgabeformat
Das Script gibt strukturierte, lesbare Ausgaben mit verschiedenen Abschnitten:
```
================================================================================
SCHNELLÜBERSICHT
================================================================================
📊 Projekt-Statistiken:
• Entities 21
• PHP Classes 1
• Workflows 1
• JavaScript Files 10
...
================================================================================
ENTITÄTEN ANALYSE
================================================================================
────────────────────────────────────────────────────────────────────────────────
► Entität: CMietobjekt
────────────────────────────────────────────────────────────────────────────────
📋 Scope:
• entity: CMietobjekt
• acl: True
• stream: False
...
🔧 Felder (15):
• name: varchar [REQUIRED] [CUSTOM]
• adresse: link → CAdressen
• miete: currency (€)
...
🔗 Beziehungen (8):
• mietverhltnisse [hasMany] → CVmhMietverhltnis.mietobjekt
• kontakte [hasMany] → Contact.mietobjekte
...
⚡ Formula Scripts:
• beforeSaveApiScript: 25 Zeilen
```
## Was wird analysiert?
### 1. Entitäten (entityDefs)
Für jede Custom Entity:
- Alle Felder mit Typ, Optionen, Constraints
- Alle Beziehungen (Links) zu anderen Entities
- Formula Scripts (beforeSave, afterSave, etc.)
- Scope-Konfiguration (ACL, Stream, Portal-Access)
### 2. Beziehungsgraph
Visualisiert alle Beziehungen zwischen Entities:
- hasMany, belongsTo, hasOne, manyToMany
- Bidirektionale Links mit relationName
- Foreign Keys
### 3. Custom PHP Klassen
Alle PHP-Dateien in `custom/Espo/Custom/Classes/`:
- FormulaFunctions
- Services
- Controllers
- Hooks
- Etc.
### 4. Workflows
Alle Workflows in `custom/workflows/`:
- Name und Status (aktiv/inaktiv)
- Trigger-Typ
- Entity-Zuordnung
- Anzahl der Aktionen
### 5. Frontend
- **JavaScript:** Alle Custom Views und Module
- **CSS:** Registrierte Stylesheets
- **App Config:** cssList, scriptList aus client.json
### 6. Layouts
Custom Layouts für jede Entity:
- detail, list, detailSmall, listSmall
- bottomPanelsDetail, sidePanelsDetail
- Etc.
### 7. Internationalisierung
- Unterstützte Sprachen
- Anzahl Übersetzungsdateien pro Sprache
- Geschätzte Anzahl Labels
## Typische Anwendungsfälle
### Fall 1: Neue Programmieraufgabe
```bash
# KI erhält vollständigen Projekt-Kontext
python3 custom/scripts/ki_project_overview.py
```
Die KI kann dann direkt auf Basis der Ausgabe arbeiten, ohne weitere Dateien lesen zu müssen.
### Fall 2: Beziehungen verstehen
Das Script zeigt automatisch alle Beziehungen zwischen Entities und hilft, Abhängigkeiten zu verstehen.
### Fall 3: Vollständigkeitsprüfung
Schnell erkennen, ob alle erwarteten Entities, Felder und Beziehungen vorhanden sind.
## Integration mit validate_and_rebuild.py
Das KI-Einstiegsscript ist als Ergänzung zum `validate_and_rebuild.py` Script konzipiert:
1. **ki_project_overview.py** → Informationen sammeln, Kontext für KI bereitstellen
2. **validate_and_rebuild.py** → Änderungen validieren und anwenden
### Typischer Workflow
```bash
# 1. Projekt-Übersicht für KI
python3 custom/scripts/ki_project_overview.py
# 2. KI macht Änderungen an JSON-Dateien
# (Basierend auf der Übersicht)
# 3. Validieren und Rebuild
python3 custom/scripts/validate_and_rebuild.py
```
## Technische Details
### Dateisystem-Struktur
Das Script erwartet folgende Struktur:
```
/var/lib/docker/volumes/vmh-espocrm_espocrm/_data/
├── README.md
├── custom/
│ ├── Espo/
│ │ └── Custom/
│ │ ├── Classes/
│ │ └── Resources/
│ │ ├── metadata/
│ │ │ ├── entityDefs/
│ │ │ ├── scopes/
│ │ │ ├── formula/
│ │ │ ├── layouts/
│ │ │ └── ...
│ │ └── i18n/
│ ├── scripts/
│ └── workflows/
└── client/
└── custom/
├── src/
└── css/
```
### Performance
- Analysiert ~20 Entities in <1 Sekunde
- JSON-Parsing mit Error-Handling
- Effiziente Rekursion durch Dateisystem
### Error-Handling
- Fehlerhafte JSON-Dateien werden übersprungen mit Fehlermeldung
- Fehlende Verzeichnisse führen zu Info-Meldungen, nicht zu Abbruch
- Robuste Exception-Behandlung
## Ausgabe-Sektionen im Detail
### 1. SCHNELLÜBERSICHT
Kompakte Statistiken für schnellen Überblick
### 2. README.md
Vollständiger Inhalt der Projektdokumentation
### 3. ENTITÄTEN ANALYSE
Detaillierte Analyse jeder Custom Entity:
- Scope (ACL, Stream, Portal, etc.)
- Felder (Typ, Constraints, Optionen)
- Beziehungen (Links zu anderen Entities)
- Formula Scripts
### 4. BEZIEHUNGSGRAPH
Visualisierung aller Entity-Beziehungen
### 5. CUSTOM LAYOUTS
Übersicht über angepasste Layouts
### 6. CUSTOM PHP KLASSEN
Alle PHP-Dateien gruppiert nach Typ
### 7. WORKFLOWS
Status und Konfiguration aller Workflows
### 8. FRONTEND ANPASSUNGEN
JavaScript, CSS und App-Konfiguration
### 9. INTERNATIONALISIERUNG
Unterstützte Sprachen und Labels
## Erweiterungen
Das Script kann leicht erweitert werden:
### Neue Analyse-Funktion hinzufügen
```python
def analyze_new_feature():
"""Analysiert neues Feature."""
print_section("NEUES FEATURE", "=")
# Implementierung
...
# In main() Funktion aufrufen
def main():
...
analyze_new_feature()
...
```
### Ausgabeformat ändern
Die Ausgabe kann angepasst werden:
- JSON-Format für maschinelle Verarbeitung
- Markdown für Dokumentation
- HTML für Browser-Darstellung
## Best Practices
### Für KI-Integration
1. **Vollständige Ausgabe verwenden:** Nicht abschneiden, KI braucht alle Details
2. **Regelmäßig aktualisieren:** Bei Projekt-Änderungen erneut ausführen
3. **Mit README.md kombinieren:** Script gibt automatisch README aus
### Für Menschen
1. **Ausgabe in Datei speichern:** Für spätere Referenz
2. **Abschnitte einzeln betrachten:** Ausgabe ist strukturiert und scrollbar
3. **Mit grep filtern:** `python3 ... | grep "Entity:"`
## Troubleshooting
### Problem: Script findet keine Entities
**Lösung:** Prüfe, ob `BASE_PATH` korrekt gesetzt ist:
```python
BASE_PATH = Path("/var/lib/docker/volumes/vmh-espocrm_espocrm/_data")
```
### Problem: JSON Parse-Fehler
**Lösung:** Script gibt Fehler aus, aber läuft weiter. Prüfe betroffene Datei mit:
```bash
python3 -m json.tool < file.json
```
### Problem: Keine README.md Ausgabe
**Lösung:** Prüfe ob `README.md` im Root-Verzeichnis existiert
## Siehe auch
- `/custom/CUSTOM_DIRECTORY.md` - Detaillierte Verzeichnisstruktur
- `custom/scripts/validate_and_rebuild.py` - Validierung und Rebuild
- `custom/scripts/VALIDATOR_README.md` - Validator-Dokumentation
- `README.md` - Hauptdokumentation
## Lizenz
Teil des EspoCRM Custom Directory, gleiches Lizenzmodell wie Hauptprojekt.
---
**Erstellt:** Januar 2026
**Autor:** Automatische KI-Integration
**Version:** 1.0

View File

@@ -0,0 +1,247 @@
# KI-Einstiegsscript Projekt - Zusammenfassung
## Erstellte Dateien
### 1. Haupt-Python-Script
**Datei:** `custom/scripts/ki_project_overview.py`
- Vollständige Projekt-Analyse
- 3376+ Zeilen Output
- Analysiert automatisch:
- ✅ 21 Custom Entities mit Feldern und Beziehungen
- ✅ Relationship-Graph
- ✅ 1 Custom PHP Klasse
- ✅ 1 Workflow
- ✅ 10 JavaScript Files
- ✅ 2 CSS Files
- ✅ 3 Custom Layouts
- ✅ 35 Sprachen (i18n)
### 2. Bash Wrapper-Script
**Datei:** `custom/scripts/ki-overview.sh`
Komfortable Nutzung mit Optionen:
```bash
./custom/scripts/ki-overview.sh # Vollständige Ausgabe
./custom/scripts/ki-overview.sh --stats # Nur Statistiken
./custom/scripts/ki-overview.sh --entities # Nur Entitäten
./custom/scripts/ki-overview.sh --relations # Nur Beziehungsgraph
./custom/scripts/ki-overview.sh --file # In Datei speichern
./custom/scripts/ki-overview.sh --help # Hilfe
```
### 3. Dokumentation
**Datei:** `custom/scripts/KI_OVERVIEW_README.md`
Umfassende Dokumentation mit:
- Zweck und Verwendung
- Ausgabeformat-Beschreibung
- Anwendungsfälle
- Integration mit validate_and_rebuild.py
- Technische Details
- Erweiterungsmöglichkeiten
- Troubleshooting
### 4. README.md Update
**Datei:** `README.md` (Schnellstart-Sektion hinzugefügt)
Neuer Abschnitt am Anfang:
```markdown
## 🚀 Schnellstart für KI
**NEU:** Automatisches KI-Einstiegsscript für vollständigen Projekt-Überblick!
```
## Verwendung für KI
### Szenario 1: Neue Programmieraufgabe
```bash
# KI erhält vollständigen Kontext
./custom/scripts/ki-overview.sh > /tmp/overview.txt
# Output an KI übergeben
cat /tmp/overview.txt
```
Die KI erhält:
- README.md (vollständig, 2112 Zeilen)
- Alle 21 Entities mit Feldern, Typen, Constraints
- Alle Beziehungen (hasMany, belongsTo, etc.)
- Custom PHP Klassen
- Workflows (Status, Aktionen)
- Frontend-Code (JS, CSS)
- i18n Sprachen
### Szenario 2: Schneller Überblick
```bash
# Nur Statistiken
./custom/scripts/ki-overview.sh --stats
```
Zeigt:
```
📊 Projekt-Statistiken:
• Entities 21
• PHP Classes 1
• Workflows 1
• JavaScript Files 10
• CSS Files 2
• Custom Layouts 3
• Languages 35
```
### Szenario 3: Beziehungen verstehen
```bash
# Nur Beziehungsgraph
./custom/scripts/ki-overview.sh --relations
```
Zeigt alle Entity-Beziehungen:
```
CMietobjekt:
⇄ mietverhltnisse [hasMany] → CVmhMietverhltnis
⇄ kontakte [hasMany] → Contact
→ vermieter [belongsTo] → CVmhVermieter
...
```
## Vorteile
### Für KI
1. **Vollständiger Kontext:** Keine manuellen Dateiabfragen nötig
2. **Aktuell:** Immer auf dem neuesten Stand
3. **Strukturiert:** Klare Sektionen, leicht zu parsen
4. **Umfassend:** README + automatische Analyse
### Für Entwickler
1. **Zeitersparnis:** Keine manuelle Dokumentation
2. **Übersichtlich:** Alle Infos an einem Ort
3. **Wartbar:** Automatisch generiert, immer korrekt
4. **Flexibel:** Verschiedene Output-Optionen
## Integration in Workflow
```
┌─────────────────────────────────────┐
│ 1. KI-Einstiegsscript ausführen │
│ ./custom/scripts/ki-overview.sh │
└───────────────┬─────────────────────┘
┌─────────────────────────────────────┐
│ 2. KI erhält Projekt-Kontext │
│ - README.md │
│ - Entities & Felder │
│ - Beziehungen │
│ - Custom Code │
└───────────────┬─────────────────────┘
┌─────────────────────────────────────┐
│ 3. KI macht Änderungen │
│ - Erstellt/bearbeitet JSON │
│ - Fügt Felder hinzu │
│ - Definiert Beziehungen │
└───────────────┬─────────────────────┘
┌─────────────────────────────────────┐
│ 4. Validierung & Rebuild │
│ ./custom/scripts/ │
│ validate_and_rebuild.py │
└─────────────────────────────────────┘
```
## Technische Details
### Performance
- Analysiert 21 Entities in < 1 Sekunde
- 3376 Zeilen Output
- Effiziente JSON-Parsing mit Error-Handling
### Robustheit
- Fehlerhafte JSON-Dateien werden übersprungen
- Fehlende Verzeichnisse = Info, kein Abbruch
- Umfangreiche Exception-Behandlung
### Erweiterbarkeit
Neue Analysen können einfach hinzugefügt werden:
```python
def analyze_new_feature():
"""Analysiert neues Feature."""
print_section("NEUES FEATURE", "=")
# Implementierung
...
# In main() aufrufen
def main():
...
analyze_new_feature()
```
## Ausgabe-Beispiel (Auszug)
```
================================================================================
ENTITÄTEN ANALYSE
================================================================================
────────────────────────────────────────────────────────────────────────────────
► Entität: CMietobjekt
────────────────────────────────────────────────────────────────────────────────
📋 Scope:
• entity: CMietobjekt
• acl: True
• stream: False
• type: BasePlus
• customizable: True
🔧 Felder (15):
• name: varchar [REQUIRED] [CUSTOM]
• adresse: link → CAdressen
• miete: currency (€)
• kaution: currency (€)
• flaeche: float
• zimmer: int
• etage: varchar
• lage: enum (options: 5)
...
🔗 Beziehungen (8):
• mietverhltnisse [hasMany] → CVmhMietverhltnis.mietobjekt (relationName: cMietobjektCVmhMietverhltnis)
• kontakte [hasMany] → Contact.mietobjekte (relationName: cMietobjektContact)
• vermieter [belongsTo] → CVmhVermieter.mietobjekte
...
```
## Nächste Schritte
### Für KI-Integration
1. ✅ Script erstellt und getestet
2. ✅ Dokumentation vollständig
3. ✅ README.md aktualisiert
4. ⏭️ In KI-Workflow integrieren
5. ⏭️ Feedback sammeln und optimieren
### Mögliche Erweiterungen
- [ ] JSON-Output für maschinelle Verarbeitung
- [ ] Markdown-Output für Dokumentation
- [ ] HTML-Output für Browser
- [ ] Filter-Optionen (z.B. nur bestimmte Entities)
- [ ] Diff-Modus (Änderungen seit letztem Lauf)
- [ ] Integration mit Git (zeige geänderte Entities)
## Siehe auch
- `custom/scripts/validate_and_rebuild.py` - Validierung & Rebuild
- `custom/scripts/VALIDATOR_README.md` - Validator-Dokumentation
- `custom/CUSTOM_DIRECTORY.md` - Custom Directory Struktur
- `README.md` - Haupt-Projektdokumentation
---
**Erstellt:** 25. Januar 2026
**Status:** ✅ Produktionsbereit
**Version:** 1.0

100
custom/scripts/ki-overview.sh Executable file
View File

@@ -0,0 +1,100 @@
#!/bin/bash
#
# KI-Einstiegsscript Wrapper
# ==========================
# Führt ki_project_overview.py aus und bietet verschiedene Ausgabeoptionen
#
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
PYTHON_SCRIPT="$SCRIPT_DIR/ki_project_overview.py"
# Farben
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
# Hilfe anzeigen
show_help() {
cat << EOF
KI-Einstiegsscript für EspoCRM Projekt
======================================
Verwendung: $0 [OPTION]
Optionen:
(keine) Vollständige Ausgabe auf stdout
-f, --file Ausgabe in Datei speichern (/tmp/ki-overview.txt)
-s, --stats Nur Schnellübersicht anzeigen
-e, --entities Nur Entitäten-Analyse
-r, --relations Nur Beziehungsgraph
-h, --help Diese Hilfe anzeigen
Beispiele:
$0 # Vollständige Analyse
$0 --file # In Datei speichern
$0 --stats # Nur Statistiken
Das Script analysiert automatisch:
✓ Custom Entitäten und Felder
✓ Beziehungen zwischen Entitäten
✓ Custom PHP Klassen
✓ Workflows
✓ Frontend-Anpassungen
✓ Internationalisierung
Weitere Dokumentation: $SCRIPT_DIR/KI_OVERVIEW_README.md
EOF
}
# Prüfe ob Python-Script existiert
if [ ! -f "$PYTHON_SCRIPT" ]; then
echo -e "${YELLOW}Fehler:${NC} Python-Script nicht gefunden: $PYTHON_SCRIPT"
exit 1
fi
# Wechsle in Projektverzeichnis
cd "$PROJECT_ROOT" || exit 1
# Optionen verarbeiten
case "${1:-}" in
-h|--help)
show_help
exit 0
;;
-f|--file)
OUTPUT_FILE="${2:-/tmp/ki-overview.txt}"
echo -e "${BLUE}Führe Projekt-Analyse durch...${NC}"
python3 "$PYTHON_SCRIPT" > "$OUTPUT_FILE" 2>&1
LINES=$(wc -l < "$OUTPUT_FILE")
echo -e "${GREEN}✓ Analyse abgeschlossen${NC}"
echo -e " Ausgabe gespeichert in: ${YELLOW}$OUTPUT_FILE${NC}"
echo -e " Zeilen: $LINES"
echo ""
echo -e "Zum Anzeigen:"
echo -e " less $OUTPUT_FILE"
echo -e " cat $OUTPUT_FILE"
;;
-s|--stats)
echo -e "${BLUE}Schnellübersicht...${NC}"
python3 "$PYTHON_SCRIPT" 2>&1 | head -n 30
;;
-e|--entities)
echo -e "${BLUE}Entitäten-Analyse...${NC}"
python3 "$PYTHON_SCRIPT" 2>&1 | sed -n '/ENTITÄTEN ANALYSE/,/BEZIEHUNGSGRAPH/p' | head -n -3
;;
-r|--relations)
echo -e "${BLUE}Beziehungsgraph...${NC}"
python3 "$PYTHON_SCRIPT" 2>&1 | sed -n '/BEZIEHUNGSGRAPH/,/CUSTOM LAYOUTS/p' | head -n -3
;;
"")
# Keine Option = vollständige Ausgabe
python3 "$PYTHON_SCRIPT"
;;
*)
echo -e "${YELLOW}Fehler:${NC} Unbekannte Option: $1"
echo "Verwenden Sie '$0 --help' für weitere Informationen."
exit 1
;;
esac

View File

@@ -0,0 +1,480 @@
#!/usr/bin/env python3
"""
KI-Einstiegsscript für EspoCRM Projekt
======================================
Gibt einen vollständigen Überblick über das Projekt aus:
- README.md Inhalt
- Automatisch ermittelte Projektstruktur
- Entitäten und ihre Felder
- Beziehungen zwischen Entitäten
- Custom PHP Klassen
- Workflows
- Frontend Anpassungen
Ziel: KI erhält aktuellen Informationsstand für die Programmierung
"""
import json
import os
from pathlib import Path
from collections import defaultdict
from typing import Dict, List, Set
# Basis-Pfad des Projekts
BASE_PATH = Path("/var/lib/docker/volumes/vmh-espocrm_espocrm/_data")
CUSTOM_PATH = BASE_PATH / "custom/Espo/Custom"
README_PATH = BASE_PATH / "README.md"
def print_section(title: str, symbol: str = "="):
"""Gibt eine formatierte Section-Überschrift aus."""
print(f"\n{symbol * 80}")
print(f"{title.center(80)}")
print(f"{symbol * 80}\n")
def print_subsection(title: str):
"""Gibt eine Unterüberschrift aus."""
print(f"\n{'' * 80}")
print(f"{title}")
print(f"{'' * 80}")
def read_readme():
"""Liest und gibt den README.md Inhalt aus."""
print_section("README.md - Projektdokumentation", "=")
if README_PATH.exists():
with open(README_PATH, 'r', encoding='utf-8') as f:
content = f.read()
print(content)
else:
print("⚠️ README.md nicht gefunden!")
def analyze_entities():
"""Analysiert alle Custom Entitäten und ihre Definitionen."""
print_section("ENTITÄTEN ANALYSE", "=")
entity_defs_path = CUSTOM_PATH / "Resources/metadata/entityDefs"
scopes_path = CUSTOM_PATH / "Resources/metadata/scopes"
if not entity_defs_path.exists():
print("⚠️ Keine Custom Entitäten gefunden!")
return {}
entities = {}
# Alle entityDefs Dateien durchgehen
for entity_file in sorted(entity_defs_path.glob("*.json")):
entity_name = entity_file.stem
try:
with open(entity_file, 'r', encoding='utf-8') as f:
entity_def = json.load(f)
# Scope-Informationen laden
scope_info = {}
scope_file = scopes_path / f"{entity_name}.json"
if scope_file.exists():
with open(scope_file, 'r', encoding='utf-8') as f:
scope_info = json.load(f)
entities[entity_name] = {
'def': entity_def,
'scope': scope_info,
'file': entity_file
}
print_subsection(f"Entität: {entity_name}")
# Scope Informationen
if scope_info:
print("\n📋 Scope:")
for key, value in scope_info.items():
if key in ['entity', 'module', 'object', 'tab', 'acl', 'customizable',
'stream', 'disabled', 'type', 'isCustom']:
print(f"{key}: {value}")
# Felder
if 'fields' in entity_def and entity_def['fields']:
print(f"\n🔧 Felder ({len(entity_def['fields'])}):")
for field_name, field_def in sorted(entity_def['fields'].items()):
field_type = field_def.get('type', 'unknown')
required = " [REQUIRED]" if field_def.get('required') else ""
disabled = " [DISABLED]" if field_def.get('disabled') else ""
isCustom = " [CUSTOM]" if field_def.get('isCustom') else ""
extra_info = []
if field_type == 'enum':
options = field_def.get('options', [])
extra_info.append(f"options: {len(options)}")
elif field_type == 'link':
entity = field_def.get('entity', 'unknown')
extra_info.append(f"{entity}")
elif field_type in ['varchar', 'text']:
if 'maxLength' in field_def:
extra_info.append(f"max: {field_def['maxLength']}")
elif field_type == 'currency':
extra_info.append("")
extra_str = f" ({', '.join(extra_info)})" if extra_info else ""
print(f"{field_name}: {field_type}{extra_str}{required}{disabled}{isCustom}")
# Beziehungen (Links)
if 'links' in entity_def and entity_def['links']:
print(f"\n🔗 Beziehungen ({len(entity_def['links'])}):")
for link_name, link_def in sorted(entity_def['links'].items()):
link_type = link_def.get('type', 'unknown')
foreign_entity = link_def.get('entity', 'unknown')
foreign_link = link_def.get('foreign', 'N/A')
relation_name = link_def.get('relationName', '')
disabled = " [DISABLED]" if link_def.get('disabled') else ""
relation_info = f" (relationName: {relation_name})" if relation_name else ""
print(f"{link_name} [{link_type}] → {foreign_entity}.{foreign_link}{relation_info}{disabled}")
# Formula Scripts
formula_file = CUSTOM_PATH / f"Resources/metadata/formula/{entity_name}.json"
if formula_file.exists():
with open(formula_file, 'r', encoding='utf-8') as f:
formula_def = json.load(f)
print(f"\n⚡ Formula Scripts:")
for script_type in ['beforeSaveScript', 'beforeSaveApiScript', 'afterSaveScript']:
if script_type in formula_def:
script = formula_def[script_type]
lines = script.count('\n') + 1
print(f"{script_type}: {lines} Zeilen")
print()
except json.JSONDecodeError as e:
print(f"❌ Fehler beim Parsen von {entity_file.name}: {e}")
except Exception as e:
print(f"❌ Fehler bei {entity_file.name}: {e}")
return entities
def analyze_relationships(entities: Dict):
"""Analysiert Beziehungen zwischen Entitäten."""
print_section("BEZIEHUNGSGRAPH", "=")
# Sammle alle Beziehungen
relationships = defaultdict(list)
for entity_name, entity_data in entities.items():
entity_def = entity_data['def']
if 'links' not in entity_def:
continue
for link_name, link_def in entity_def['links'].items():
if link_def.get('disabled'):
continue
target_entity = link_def.get('entity')
link_type = link_def.get('type', 'unknown')
if target_entity:
relationships[entity_name].append({
'link_name': link_name,
'type': link_type,
'target': target_entity,
'foreign': link_def.get('foreign', 'N/A')
})
# Gib Beziehungsgraph aus
for entity_name in sorted(relationships.keys()):
links = relationships[entity_name]
if links:
print(f"\n{entity_name}:")
for link in links:
arrow = "" if link['type'] in ['belongsTo', 'hasOne'] else ""
print(f" {arrow} {link['link_name']} [{link['type']}] → {link['target']}")
def analyze_custom_classes():
"""Analysiert Custom PHP Klassen."""
print_section("CUSTOM PHP KLASSEN", "=")
classes_path = CUSTOM_PATH / "Classes"
if not classes_path.exists():
print(" Keine Custom PHP Klassen gefunden.")
return
php_files = list(classes_path.rglob("*.php"))
if not php_files:
print(" Keine Custom PHP Klassen gefunden.")
return
# Gruppiere nach Typ
by_type = defaultdict(list)
for php_file in php_files:
relative_path = php_file.relative_to(classes_path)
parts = relative_path.parts
if len(parts) > 0:
class_type = parts[0]
by_type[class_type].append(relative_path)
for class_type in sorted(by_type.keys()):
print(f"\n📦 {class_type}:")
for file_path in sorted(by_type[class_type]):
print(f"{file_path}")
def analyze_workflows():
"""Analysiert Workflows."""
print_section("WORKFLOWS", "=")
workflows_path = BASE_PATH / "custom/workflows"
if not workflows_path.exists():
print(" Keine Workflows gefunden.")
return
workflow_files = list(workflows_path.glob("*.json"))
if not workflow_files:
print(" Keine Workflows gefunden.")
return
for workflow_file in sorted(workflow_files):
try:
with open(workflow_file, 'r', encoding='utf-8') as f:
workflow = json.load(f)
name = workflow.get('name', workflow_file.stem)
entity = workflow.get('entityType', 'N/A')
is_active = workflow.get('isActive', False)
status = "✓ AKTIV" if is_active else "✗ INAKTIV"
print(f"\n📋 {name} ({workflow_file.name})")
print(f" Entität: {entity}")
print(f" Status: {status}")
# Trigger-Typ
if 'type' in workflow:
print(f" Trigger: {workflow['type']}")
# Aktionen
if 'actions' in workflow:
actions = workflow['actions']
print(f" Aktionen ({len(actions)}):")
for action in actions[:5]: # Erste 5 Aktionen
action_type = action.get('type', 'unknown')
print(f"{action_type}")
if len(actions) > 5:
print(f" ... und {len(actions) - 5} weitere")
except Exception as e:
print(f"❌ Fehler beim Lesen von {workflow_file.name}: {e}")
def analyze_frontend():
"""Analysiert Frontend Anpassungen."""
print_section("FRONTEND ANPASSUNGEN", "=")
# JavaScript
js_path = BASE_PATH / "client/custom/src"
if js_path.exists():
js_files = list(js_path.rglob("*.js"))
if js_files:
print_subsection("JavaScript Files")
for js_file in sorted(js_files):
relative = js_file.relative_to(js_path)
print(f"{relative}")
# CSS
css_path = BASE_PATH / "client/custom/css"
if css_path.exists():
css_files = list(css_path.glob("*.css"))
if css_files:
print_subsection("CSS Files")
for css_file in sorted(css_files):
print(f"{css_file.name}")
# App Client Config
client_config = CUSTOM_PATH / "Resources/metadata/app/client.json"
if client_config.exists():
print_subsection("App Client Config")
try:
with open(client_config, 'r', encoding='utf-8') as f:
config = json.load(f)
if 'cssList' in config:
print(" CSS List:")
for css in config['cssList']:
if css != "__APPEND__":
print(f"{css}")
if 'scriptList' in config:
print(" Script List:")
for script in config['scriptList']:
if script != "__APPEND__":
print(f"{script}")
except Exception as e:
print(f" ❌ Fehler: {e}")
def analyze_layouts():
"""Analysiert Custom Layouts."""
print_section("CUSTOM LAYOUTS", "=")
layouts_path = CUSTOM_PATH / "Resources/metadata/layouts"
if not layouts_path.exists():
print(" Keine Custom Layouts gefunden.")
return
# Gruppiere nach Entität
entities = defaultdict(list)
for layout_file in layouts_path.rglob("*.json"):
relative = layout_file.relative_to(layouts_path)
entity = relative.parts[0] if len(relative.parts) > 1 else "unknown"
layout_type = relative.stem
entities[entity].append(layout_type)
for entity in sorted(entities.keys()):
layouts = sorted(entities[entity])
print(f"\n{entity}:")
print(f" Layouts: {', '.join(layouts)}")
def analyze_i18n():
"""Analysiert Internationalisierung."""
print_section("INTERNATIONALISIERUNG (i18n)", "=")
i18n_path = CUSTOM_PATH / "Resources/i18n"
if not i18n_path.exists():
print(" Keine i18n Dateien gefunden.")
return
languages = [d.name for d in i18n_path.iterdir() if d.is_dir()]
print(f"Unterstützte Sprachen: {', '.join(sorted(languages))}")
for lang in sorted(languages):
lang_path = i18n_path / lang
json_files = list(lang_path.glob("*.json"))
if json_files:
print(f"\n{lang}:")
print(f" Übersetzungsdateien: {len(json_files)}")
# Zähle Labels
total_labels = 0
for json_file in json_files:
try:
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
# Rekursiv Labels zählen
def count_labels(obj):
if isinstance(obj, dict):
return sum(count_labels(v) for v in obj.values())
elif isinstance(obj, str):
return 1
return 0
total_labels += count_labels(data)
except:
pass
print(f" Geschätzte Labels: ~{total_labels}")
def print_quick_stats():
"""Gibt eine Schnellübersicht aus."""
print_section("SCHNELLÜBERSICHT", "=")
stats = {}
# Entitäten
entity_defs_path = CUSTOM_PATH / "Resources/metadata/entityDefs"
if entity_defs_path.exists():
stats['Entities'] = len(list(entity_defs_path.glob("*.json")))
# PHP Klassen
classes_path = CUSTOM_PATH / "Classes"
if classes_path.exists():
stats['PHP Classes'] = len(list(classes_path.rglob("*.php")))
# Workflows
workflows_path = BASE_PATH / "custom/workflows"
if workflows_path.exists():
stats['Workflows'] = len(list(workflows_path.glob("*.json")))
# JS Files
js_path = BASE_PATH / "client/custom/src"
if js_path.exists():
stats['JavaScript Files'] = len(list(js_path.rglob("*.js")))
# CSS Files
css_path = BASE_PATH / "client/custom/css"
if css_path.exists():
stats['CSS Files'] = len(list(css_path.glob("*.css")))
# Layouts
layouts_path = CUSTOM_PATH / "Resources/metadata/layouts"
if layouts_path.exists():
stats['Custom Layouts'] = len(list(layouts_path.rglob("*.json")))
# i18n
i18n_path = CUSTOM_PATH / "Resources/i18n"
if i18n_path.exists():
languages = [d.name for d in i18n_path.iterdir() if d.is_dir()]
stats['Languages'] = len(languages)
print("📊 Projekt-Statistiken:\n")
for key, value in stats.items():
print(f"{key:<20} {value:>5}")
def main():
"""Hauptfunktion - führt alle Analysen aus."""
print("\n" + "=" * 80)
print("KI-EINSTIEGSSCRIPT FÜR ESPOCRM PROJEKT".center(80))
print("Automatische Projekt-Analyse für KI-basierte Programmierung".center(80))
print("=" * 80)
# 1. Schnellübersicht
print_quick_stats()
# 2. README.md
read_readme()
# 3. Entitäten analysieren
entities = analyze_entities()
# 4. Beziehungsgraph
if entities:
analyze_relationships(entities)
# 5. Custom Layouts
analyze_layouts()
# 6. Custom PHP Klassen
analyze_custom_classes()
# 7. Workflows
analyze_workflows()
# 8. Frontend
analyze_frontend()
# 9. i18n
analyze_i18n()
# Abschluss
print_section("ANALYSE ABGESCHLOSSEN", "=")
print("\n✅ Die KI hat jetzt einen vollständigen Überblick über das Projekt!")
print(" Alle Entitäten, Beziehungen, Custom Klassen und Frontend-Anpassungen wurden erfasst.\n")
if __name__ == "__main__":
main()