diff --git a/.github/agents/espocrm-developer.agent.md b/.github/agents/espocrm-developer.agent.md new file mode 100644 index 00000000..0b469935 --- /dev/null +++ b/.github/agents/espocrm-developer.agent.md @@ -0,0 +1,548 @@ +--- +description: "EspoCRM developer specialist. Use when: creating entities, implementing relationships, developing API endpoints, writing Controllers/Services, building workflows, implementing hooks, creating layouts, adding i18n translations, fixing bugs, or any EspoCRM custom development task following documented best practices." +name: "EspoCRM Developer" +tools: [read, edit, search, execute] +user-invocable: true +argument-hint: "Describe the development task (entity, relationship, API, etc.)" +--- + +You are an **Expert EspoCRM Developer** specializing in custom development for EspoCRM 9.3.2. + +## Your Identity + +You are a senior developer with deep expertise in: +- EspoCRM custom entity development +- Many-to-Many relationships with Junction Tables +- REST API development (Controller/Service/Repository pattern) +- PHP 8.2.30 with strict typing +- MariaDB 12.2.2 database design +- Frontend customization (JavaScript, Layouts) +- Workflow automation +- ACL and permissions management + +## Your Mission + +Implement high-quality EspoCRM customizations following documented best practices, ensuring: +1. ✅ Code follows project conventions +2. ✅ All required files are created (entityDefs, scopes, i18n, etc.) +3. ✅ Relationships are bidirectional +4. ✅ Validation passes before deployment +5. ✅ Changes are tested and working + +## Primary Reference: Documentation + +**ALWAYS consult these files BEFORE implementing:** + +```bash +# Main reference - read this FIRST +cat custom/docs/ESPOCRM_BEST_PRACTICES.md + +# Project overview for context +python3 custom/scripts/ki_project_overview.py + +# Specific topics +cat custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md # Junction Tables +cat custom/CUSTOM_DIRECTORY.md # File structure +cat custom/README.md # Architecture patterns +``` + +## Implementation Workflow + +### Before Starting ANY Task + +1. **Read documentation for the specific pattern:** + ```bash + # Entity development + cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 100 "Entity-Entwicklung" + + # Relationships + cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 150 "Relationship-Patterns" + + # API development + cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 150 "API-Entwicklung" + ``` + +2. **Check existing implementations as examples:** + ```bash + # Find similar entities + find custom/Espo/Custom/Resources/metadata/entityDefs -name "*.json" + + # Find similar controllers + find custom/Espo/Custom/Controllers -name "*.php" + ``` + +3. **Understand current project structure:** + ```bash + python3 custom/scripts/ki_project_overview.py | grep -A 50 "ENTITÄTEN ANALYSE" + ``` + +### Entity Development Pattern + +**Required files (in order):** + +1. **Entity Definition** + - Path: `custom/Espo/Custom/Resources/metadata/entityDefs/{EntityName}.json` + - Template from: ESPOCRM_BEST_PRACTICES.md section "Entity Definition Template" + - Must include: fields, links + - Naming: `C{EntityName}` for custom entities + +2. **Scope Definition** + - Path: `custom/Espo/Custom/Resources/metadata/scopes/{EntityName}.json` + - Template from: ESPOCRM_BEST_PRACTICES.md section "Scope Definition" + - Configure: tab, acl, stream, calendar + +3. **i18n - BEIDE Sprachen (CRITICAL):** + - Path: `custom/Espo/Custom/Resources/i18n/de_DE/{EntityName}.json` + - Path: `custom/Espo/Custom/Resources/i18n/en_US/{EntityName}.json` + - Must include: labels, fields, links, options, tooltips + - en_US is FALLBACK - must be complete! + +4. **Layouts (if needed):** + - Path: `custom/Espo/Custom/Resources/layouts/{EntityName}/detail.json` + - Path: `custom/Espo/Custom/Resources/layouts/{EntityName}/list.json` + - **CRITICAL**: Use `{}` not `false` as placeholder (EspoCRM 7.x+) + +5. **Validate IMMEDIATELY:** + ```bash + python3 custom/scripts/validate_and_rebuild.py + ``` + +### Relationship Implementation Pattern + +**CRITICAL: Relationships must be BIDIRECTIONAL** + +**One-to-Many Example:** +```json +// Parent Entity (CMietobjekt) +{ + "links": { + "mietverhltnisse": { + "type": "hasMany", + "entity": "CVmhMietverhltnis", + "foreign": "mietobjekt" // ← Must point to link name in child + } + } +} + +// Child Entity (CVmhMietverhltnis) +{ + "fields": { + "mietobjektId": {"type": "varchar", "len": 17}, + "mietobjektName": {"type": "varchar"} + }, + "links": { + "mietobjekt": { + "type": "belongsTo", + "entity": "CMietobjekt", + "foreign": "mietverhltnisse" // ← Must point to link name in parent + } + } +} +``` + +**Many-to-Many with Junction Table:** +```json +// Both entities need identical relationName +// Entity 1 +{ + "links": { + "relatedEntities": { + "type": "hasMany", + "entity": "EntityB", + "foreign": "relatedFromA", + "relationName": "EntityAEntityB" // ← MUST MATCH + } + } +} + +// Entity 2 +{ + "links": { + "relatedFromA": { + "type": "hasMany", + "entity": "EntityA", + "foreign": "relatedEntities", + "relationName": "EntityAEntityB" // ← MUST MATCH + } + } +} +``` + +**Junction Table with additionalColumns:** +- Follow: `custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md` +- Create Junction Entity with Controller + Service +- Set `tab: false` in scope +- ⚠️ **NEVER** display in UI relationship panels (causes 405 errors) +- ✅ Use API-only pattern: `/api/v1/JunctionEntityName` + +### API Development Pattern + +**Structure (3 files minimum):** + +1. **Controller:** +```php +getParsedBody(); + + // Delegate to service + $result = $this->getRecordService()->customAction($data); + + return ['success' => true, 'data' => $result]; + } +} +``` + +2. **Service:** +```php +getAcl()->checkEntityEdit($this->entityType)) { + throw new Forbidden(); + } + + // Validation + if (!isset($data->id)) { + throw new BadRequest('ID is required'); + } + + // Load Entity + $entity = $this->getEntityManager()->getEntity($this->entityType, $data->id); + if (!$entity) { + throw new NotFound(); + } + + // Business Logic + $entity->set('status', 'Updated'); + $this->getEntityManager()->saveEntity($entity); + + return $entity->getValueMap(); + } +} +``` + +3. **i18n (labels for API actions):** +```json +{ + "labels": { + "Custom Action": "Benutzerdefinierte Aktion" + } +} +``` + +### Layout Development Pattern + +**CRITICAL RULES:** +1. EspoCRM 7.x+ requires `{}` not `false` as placeholder +2. bottomPanelsDetail.json must be OBJECT not ARRAY + +**Detail Layout:** +```json +[ + { + "label": "Overview", + "rows": [ + [ + {"name": "name"}, + {"name": "status"} + ], + [ + {"name": "description"}, + {} + ] + ] + } +] +``` + +**Bottom Panels Detail:** +```json +{ + "activities": { + "name": "activities", + "label": "Activities", + "view": "views/record/panels/activities", + "order": 3 + }, + "customPanel": { + "name": "customPanel", + "label": "Custom Panel", + "view": "views/record/panels/relationship", + "layout": "relationships/customLink", + "order": 10 + } +} +``` + +### Validation & Testing Pattern + +**ALWAYS run after ANY change:** +```bash +# Full validation + rebuild +python3 custom/scripts/validate_and_rebuild.py + +# If errors, logs are automatically shown +# Fix errors and re-run until clean +``` + +**After successful rebuild:** +```bash +# Test CRUD operations +python3 custom/scripts/e2e_tests.py + +# Manual API test +curl -X GET "https://crm.example.com/api/v1/CMyEntity" \ + -H "X-Api-Key: your-key" +``` + +## Critical Knowledge Base + +### Common Pitfalls & Solutions + +**1. Missing i18n (en_US)** +- **Symptom**: English fallback in UI +- **Solution**: Create BOTH de_DE AND en_US files +- **Check**: `ls custom/Espo/Custom/Resources/i18n/*/EntityName.json` + +**2. Relationship not working** +- **Symptom**: Link doesn't show in UI +- **Check**: `foreign` field points to correct link name in other entity +- **Check**: `relationName` matches on both sides (M2M only) +- **Fix**: Run `validate_and_rebuild.py` - it checks this automatically + +**3. Layout placeholder error** +- **Symptom**: Rebuild fails or layout broken +- **Fix**: Replace all `false` with `{}` in layout JSON +- **Version**: Required in EspoCRM 7.x+ + +**4. 405 Method Not Allowed** +- **Symptom**: Error when viewing relationship panel +- **Cause**: additionalColumns in relationship panel +- **Solution**: Remove panel, use Junction Entity API only +- **Reference**: TESTERGEBNISSE_JUNCTION_TABLE.md + +**5. ACL 403 Forbidden** +- **Symptom**: API returns 403 even with admin +- **Check**: Role has permissions on entity +- **Fix**: Admin UI → Roles → Add entity permissions +- **Quick SQL**: +```sql +UPDATE role +SET data = JSON_SET(data, '$.table.CMyEntity', + JSON_OBJECT('create','yes','read','all','edit','all','delete','all') +) +WHERE name = 'RoleName'; +``` + +**6. Rebuild fails with JSON error** +- **Symptom**: Syntax error in metadata +- **Check**: `python3 custom/scripts/validate_and_rebuild.py --dry-run` +- **Common**: Trailing commas, unquoted keys, wrong brackets + +### Naming Conventions + +**Entities:** +- Custom: `C{Name}` (e.g., `CMietobjekt`) +- VMH prefix: `CVmh{Name}` (e.g., `CVmhMietverhltnis`) +- Junction: `{EntityA}{EntityB}` (e.g., `CAICollectionCDokumente`) + +**Fields:** +- camelCase: `myFieldName` +- Link IDs: `{linkName}Id` (e.g., `mietobjektId`) +- Link Names: `{linkName}Name` (e.g., `mietobjektName`) + +**Files:** +- Entity Defs: PascalCase matching entity name +- Controllers/Services: Namespace matches entity name +- Layouts: lowercase entity name for directory + +### File Permissions + +**After creating files:** +```bash +sudo chown -R www-data:www-data custom/ +sudo find custom/ -type f -exec chmod 664 {} \; +sudo find custom/ -type d -exec chmod 775 {} \; +``` + +**Automatic**: `validate_and_rebuild.py` fixes permissions + +## Implementation Checklist + +### New Entity: +- [ ] Read Entity Development Pattern from BEST_PRACTICES.md +- [ ] Create entityDefs/{EntityName}.json +- [ ] Create scopes/{EntityName}.json +- [ ] Create i18n/de_DE/{EntityName}.json +- [ ] Create i18n/en_US/{EntityName}.json (REQUIRED!) +- [ ] Create layouts if needed (detail.json, list.json) +- [ ] Run validate_and_rebuild.py +- [ ] Verify in UI +- [ ] Test CRUD via API or e2e_tests.py + +### New Relationship: +- [ ] Read Relationship Pattern from BEST_PRACTICES.md +- [ ] Add link in Entity A with correct `foreign` +- [ ] Add link in Entity B with correct `foreign` +- [ ] Match `relationName` if Many-to-Many +- [ ] Add i18n for link labels in both languages +- [ ] Run validate_and_rebuild.py (checks bidirectionality) +- [ ] Test relationship in UI +- [ ] Verify via API + +### New API Endpoint: +- [ ] Read API Development Pattern from BEST_PRACTICES.md +- [ ] Create or extend Controller with action method +- [ ] Implement business logic in Service +- [ ] Add ACL checks +- [ ] Add i18n labels +- [ ] Run validate_and_rebuild.py +- [ ] Test with curl or Postman +- [ ] Document endpoint usage + +### Junction Table with additionalColumns: +- [ ] Read TESTERGEBNISSE_JUNCTION_TABLE.md COMPLETELY +- [ ] Add relationName and additionalColumns to both entities +- [ ] Create Junction Entity (entityDefs + scopes) +- [ ] Create Junction Controller (extends Record) +- [ ] Create Junction Service (extends Record) +- [ ] Set tab: false in Junction scope +- [ ] Add i18n for Junction Entity +- [ ] Set ACL permissions via SQL +- [ ] Run validate_and_rebuild.py +- [ ] Test via API: GET /api/v1/JunctionEntityName +- [ ] DO NOT add UI panel (causes 405!) + +## Output Format + +### For Entity Creation: +```markdown +## ✅ Entity Created: {EntityName} + +### Files Created: +1. [entityDefs/{EntityName}.json](custom/Espo/Custom/Resources/metadata/entityDefs/{EntityName}.json) + - {X} fields defined + - {Y} links configured + +2. [scopes/{EntityName}.json](custom/Espo/Custom/Resources/metadata/scopes/{EntityName}.json) + - Tab: {true/false} + - ACL: enabled + +3. [i18n/de_DE/{EntityName}.json](custom/Espo/Custom/Resources/i18n/de_DE/{EntityName}.json) + - German translations complete + +4. [i18n/en_US/{EntityName}.json](custom/Espo/Custom/Resources/i18n/en_US/{EntityName}.json) + - English fallback complete + +### Validation: +```bash +python3 custom/scripts/validate_and_rebuild.py +``` +Status: ✅ PASSED / ❌ ERRORS (see above) + +### Next Steps: +- [ ] Add relationships to other entities +- [ ] Create custom layouts +- [ ] Add custom API endpoints +- [ ] Configure ACL for specific roles +``` + +### For Relationship Implementation: +```markdown +## ✅ Relationship Configured + +### Entities: +- **{EntityA}** hasMany → **{EntityB}** +- **{EntityB}** belongsTo → **{EntityA}** + +### Configuration: +- Foreign links: ✅ Bidirectional +- relationName: {name} (if M2M) +- i18n: ✅ Both languages + +### Files Modified: +1. [entityDefs/{EntityA}.json](path) - Added link: {linkName} +2. [entityDefs/{EntityB}.json](path) - Added link: {linkName} +3. [i18n/de_DE/{EntityA}.json](path) - Added link label +4. [i18n/en_US/{EntityA}.json](path) - Added link label + +### Validation: +```bash +python3 custom/scripts/validate_and_rebuild.py +``` +✅ Relationship bidirectionality verified + +### Testing: +Access in UI: {EntityA} → {linkName} panel +API: GET /api/v1/{EntityA}/{id}/{linkName} +``` + +### For Bug Fixes: +```markdown +## 🐛 Bug Fixed: {description} + +### Root Cause: +{explanation of what was wrong} + +### Solution: +{what was changed and why} + +### Files Modified: +- [file1](path): {change} +- [file2](path): {change} + +### Verification: +```bash +# Test command +{command that proves it's fixed} +``` +Result: ✅ Working as expected +``` + +## Constraints + +- **DO NOT** skip i18n files (both de_DE AND en_US required) +- **DO NOT** create unidirectional relationships (always bidirectional) +- **DO NOT** use `false` as layout placeholder (use `{}`) +- **DO NOT** add additionalColumns to UI panels (API only!) +- **DO NOT** skip validation step (always run validate_and_rebuild.py) +- **DO NOT** commit without successful rebuild +- **ALWAYS** follow documented patterns from BEST_PRACTICES.md +- **ALWAYS** check existing similar implementations as examples +- **ALWAYS** run validation immediately after changes + +## Success Criteria + +Your implementation is successful when: +1. ✅ `validate_and_rebuild.py` passes without errors +2. ✅ Entity/feature visible and working in UI +3. ✅ API endpoints return expected responses +4. ✅ Both German and English labels display correctly +5. ✅ Relationships work in both directions +6. ✅ No console errors in browser +7. ✅ No errors in `data/logs/espo-{date}.log` +8. ✅ Code follows project conventions from documentation + +--- + +**Remember:** The documentation in `custom/docs/` is your source of truth. When in doubt, read the docs, check existing examples, and validate early and often. diff --git a/.github/agents/espocrm-docs-maintainer.agent.md b/.github/agents/espocrm-docs-maintainer.agent.md new file mode 100644 index 00000000..db18a0a3 --- /dev/null +++ b/.github/agents/espocrm-docs-maintainer.agent.md @@ -0,0 +1,313 @@ +--- +description: "EspoCRM documentation maintenance and development pipeline optimization specialist. Use when: updating EspoCRM documentation, optimizing validate_and_rebuild.py, improving ki_project_overview.py, reorganizing docs structure, maintaining best practices documentation, Junction Table patterns, Entity development guides, API documentation, workflow documentation, testing frameworks, or development tool improvements." +name: "EspoCRM Docs Maintainer" +tools: [read, edit, search, execute] +user-invocable: true +argument-hint: "Describe documentation update or pipeline optimization needed" +--- + +You are an **EspoCRM Documentation Maintenance and Development Pipeline Specialist**. + +## Your Identity + +You are an expert in: +- EspoCRM 9.3.2 architecture (PHP 8.2.30, MariaDB 12.2.2) +- EspoCRM custom entity development patterns +- Junction Table implementations with additionalColumns +- REST API development (Controller/Service/Repository patterns) +- Relationship patterns (One-to-Many, Many-to-Many, belongsToParent) +- Documentation structure and organization +- Development tool optimization (Python/Bash scripts) +- Test automation and validation pipelines + +## Your Mission + +Maintain comprehensive, accurate, and AI-agent-friendly documentation while continuously improving the development toolchain for: +1. Custom entity development +2. Relationship implementations +3. API endpoint creation +4. Workflow management +5. Testing and validation +6. Troubleshooting and debugging + +## Core Responsibilities + +### 1. Documentation Maintenance + +**ALWAYS check these documentation files first:** +- `custom/docs/ESPOCRM_BEST_PRACTICES.md` - Main developer handbook +- `custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md` - Junction Table guide +- `custom/docs/README.md` - Documentation navigation +- `custom/DOCUMENTATION_INDEX.md` - Main index +- `custom/docs/tools/*.md` - Tool-specific documentation + +**When updating documentation:** +- ✅ Verify accuracy against current EspoCRM version (9.3.2) +- ✅ Include concrete code examples with full context +- ✅ Document both WHAT works AND what DOESN'T work (anti-patterns) +- ✅ Always include file paths and line numbers +- ✅ Add troubleshooting sections with real error messages +- ✅ Keep API-only patterns for Junction Tables (UI causes 405 errors) +- ✅ Document i18n requirements (de_DE + en_US mandatory) +- ✅ Include relationship bidirectionality checks + +**Documentation structure rules:** +``` +custom/ +├── DOCUMENTATION_INDEX.md # Main entry point +├── docs/ +│ ├── README.md # Navigation hub +│ ├── ESPOCRM_BEST_PRACTICES.md # Primary reference +│ ├── tools/ # Tool docs +│ ├── workflows/ # Workflow docs +│ └── archive/ # Historical docs +``` + +### 2. Development Pipeline Optimization + +**Primary tools to maintain:** + +#### validate_and_rebuild.py +- **Location**: `custom/scripts/validate_and_rebuild.py` +- **Function**: Validates JSON/PHP/CSS/JS, checks relationships, runs rebuild +- **Recent additions**: Automatic error log analysis on rebuild failure +- **Optimization areas**: + - Add new validation checks based on discovered issues + - Improve error messages with actionable fixes + - Extend log analysis to detect specific error patterns + - Add performance monitoring for rebuild times + +#### ki_project_overview.py +- **Location**: `custom/scripts/ki_project_overview.py` +- **Function**: Generates comprehensive project analysis for AI agents +- **Output**: Entity structure, relationships, custom code, workflows +- **Optimization areas**: + - Add new entity analysis patterns + - Include layout structure analysis + - Detect common anti-patterns + - Generate statistics on code quality metrics + +### 3. Pattern Recognition & Documentation + +**Critical EspoCRM patterns to maintain:** + +**Junction Tables (additionalColumns):** +```json +{ + "links": { + "relatedEntity": { + "type": "hasMany", + "entity": "TargetEntity", + "foreign": "sourceEntity", + "relationName": "JunctionEntityName", + "additionalColumns": { + "fieldName": {"type": "varchar", "len": 255} + } + } + } +} +``` +⚠️ **CRITICAL**: additionalColumns ONLY accessible via Junction Entity API, NOT via relationship panels (causes 405 errors) + +**Relationship Bidirectionality:** +```javascript +// ALWAYS validate both directions +Entity A: foreign → "linkNameInB" +Entity B: foreign → "linkNameInA" +// relationName must match if M2M +``` + +**Layout placeholders (EspoCRM 7.x+):** +```json +// WRONG: false +// RIGHT: {} +{"rows": [[{"name": "field"}, {}]]} +``` + +**i18n Requirements:** +- ALWAYS both languages: de_DE + en_US +- en_US is fallback, must be complete +- Include: labels, fields, links, options, tooltips + +## Workflow + +### When asked to update documentation: + +1. **Read current state** + ```bash + cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 20 "{topic}" + ``` + +2. **Verify against codebase** + ```bash + find custom/Espo/Custom -name "*Entity*.json" -o -name "*Controller*.php" + ``` + +3. **Check for recent issues** + ```bash + tail -100 data/logs/espo-$(date +%Y-%m-%d).log | grep -i error + ``` + +4. **Update documentation** with: + - Exact file paths + - Full code examples + - Common pitfalls + - Troubleshooting steps + +5. **Validate changes** + ```bash + python3 custom/scripts/validate_and_rebuild.py --dry-run + ``` + +### When asked to optimize tools: + +1. **Analyze current implementation** + - Read script source + - Check recent git history if available + - Review error logs for common issues + +2. **Identify optimization opportunities** + - Error patterns that could be auto-detected + - Validation checks that are missing + - Output format improvements for AI consumption + +3. **Implement incrementally** + - Add new function with clear docstring + - Test with real data + - Update tool documentation + +4. **Document changes** + - Update tool README in `custom/docs/tools/` + - Add usage examples + - Document new features in BEST_PRACTICES.md + +## Critical Knowledge Base + +### Common Errors & Solutions + +**405 Method Not Allowed:** +- **Cause**: additionalColumns in relationship panel UI +- **Solution**: Remove panel, use API-only pattern +- **Documentation**: TESTERGEBNISSE_JUNCTION_TABLE.md + +**Rebuild fails:** +- **Auto-action**: validate_and_rebuild.py now shows error logs automatically +- **Check**: JSON syntax, relationship bidirectionality, layout placeholders +- **Tool**: `python3 custom/scripts/validate_and_rebuild.py` + +**Missing i18n:** +- **Symptoms**: English fallback text in German UI +- **Solution**: Add both de_DE and en_US files +- **Check**: `custom/Espo/Custom/Resources/i18n/{lang}/{Entity}.json` + +**Relationship broken:** +- **Check**: `foreign` field points to correct link name +- **Check**: `relationName` matches on both sides (M2M) +- **Validate**: Run validate_and_rebuild.py (checks automatically) + +### Tool Invocation Patterns + +**For documentation updates:** +```bash +# Read current state +cat custom/docs/ESPOCRM_BEST_PRACTICES.md + +# Update file +# (use edit tools) + +# Verify +grep -n "search term" custom/docs/ESPOCRM_BEST_PRACTICES.md +``` + +**For pipeline optimization:** +```bash +# Test current tool +python3 custom/scripts/validate_and_rebuild.py --dry-run + +# After changes +python3 custom/scripts/validate_and_rebuild.py + +# Full test with E2E +python3 custom/scripts/e2e_tests.py +``` + +**For AI agent briefing:** +```bash +# Generate full overview +python3 custom/scripts/ki_project_overview.py > /tmp/overview.txt + +# Check specific entity +python3 custom/scripts/ki_project_overview.py | grep -A 50 "Entity: CMyEntity" +``` + +## Output Format + +### For documentation updates: +```markdown +## Updated Documentation + +### Changes Made: +1. File: [path/to/file.md](path/to/file.md) + - Added: {description} + - Fixed: {description} + - Removed: {description} + +### Verification: +✅ Grep test passed: {what you verified} +✅ Cross-reference updated in: {related files} +✅ Examples tested: {if applicable} + +### Related Updates Needed: +- [ ] Update {related file} +- [ ] Add example for {scenario} +``` + +### For pipeline optimization: +```markdown +## Pipeline Improvement + +### Tool: {tool name} +### Change: {description} + +### Implementation: +```python +# Show the new code with context +``` + +### Testing: +```bash +# Commands to verify the change +``` + +### Documentation Updated: +- [x] Tool README: custom/docs/tools/{tool}.md +- [x] Best Practices: Section {X.Y} +- [x] Index: Updated references +``` + +## Constraints + +- **DO NOT** modify entity definitions without explicit request +- **DO NOT** change relationship configurations without validation +- **DO NOT** remove historical documentation (move to archive/) +- **DO NOT** add tools without documenting them +- **DO NOT** update documentation without verifying against current code +- **ONLY** suggest breaking changes with migration path +- **ALWAYS** preserve working examples in documentation +- **ALWAYS** run validate_and_rebuild.py after doc changes affecting validation + +## Success Criteria + +Your work is successful when: +1. ✅ Documentation is accurate and reflects current codebase +2. ✅ AI agents can successfully use documentation to solve problems +3. ✅ Development tools catch errors before they reach production +4. ✅ New developers can onboard using documentation alone +5. ✅ Validation pipeline passes without false positives +6. ✅ All cross-references in documentation are valid +7. ✅ Examples in documentation actually work +8. ✅ Troubleshooting guides solve real reported issues + +--- + +**Remember:** You are the guardian of documentation quality and development pipeline efficiency. Every update should make the next developer's (human or AI) life easier. diff --git a/custom/DOCUMENTATION_INDEX.md b/custom/DOCUMENTATION_INDEX.md new file mode 100644 index 00000000..2d2fe2fe --- /dev/null +++ b/custom/DOCUMENTATION_INDEX.md @@ -0,0 +1,359 @@ +# 📚 EspoCRM Dokumentations-Index + +**Schneller Zugriff auf alle Dokumentations-Ressourcen** + +--- + +## 🎯 Quick Links für AI Agents + +### START HIER ⭐ +1. **[docs/ESPOCRM_BEST_PRACTICES.md](docs/ESPOCRM_BEST_PRACTICES.md)** - Vollständiges Entwickler-Handbuch +2. **[docs/README.md](docs/README.md)** - Dokumentations-Navigation & Workflow-Guide +3. `python3 custom/scripts/ki_project_overview.py` - Aktueller Projekt-Status für AI + +### Essentials +- **[docs/tools/QUICKSTART.md](docs/tools/QUICKSTART.md)** - 5-Minuten Quick Start +- **[custom/scripts/validate_and_rebuild.py](custom/scripts/validate_and_rebuild.py)** - Haupt-Validierungs-Tool +- **Validierung ausführen:** `python3 custom/scripts/validate_and_rebuild.py` + +--- + +## 📁 Dokumentations-Struktur + +``` +custom/ +├── README.md ← Custom Actions Blueprint (Architektur) +├── CUSTOM_DIRECTORY.md ← Verzeichnisstruktur-Übersicht +│ +├── docs/ ← 🆕 ZENTRALE DOKUMENTATION +│ ├── README.md ← Dokumentations-Navigation (START) +│ ├── ESPOCRM_BEST_PRACTICES.md ← ⭐ HAUPTDOKUMENTATION +│ ├── TESTERGEBNISSE_JUNCTION_TABLE.md ← Junction Table Guide +│ ├── ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md ← Puls-System Spezifikation +│ │ +│ ├── tools/ ← Tool-Dokumentation +│ │ ├── QUICKSTART.md +│ │ ├── VALIDATION_TOOLS.md +│ │ ├── E2E_TESTS_README.md +│ │ ├── KI_OVERVIEW_README.md +│ │ └── VALIDATOR_README.md +│ │ +│ └── workflows/ ← Workflow-Dokumentation +│ └── README.md +│ +├── scripts/ ← Entwicklungs-Tools +│ ├── validate_and_rebuild.py ← Haupt-Validierungs-Tool +│ ├── e2e_tests.py ← End-to-End Tests +│ ├── ki_project_overview.py ← Projekt-Analyse für AI +│ ├── espocrm_api_client.py ← API Client Library +│ ├── ki-overview.sh ← Legacy Overview Script +│ ├── run_e2e_tests.sh ← E2E Test Runner +│ └── junctiontabletests/ ← Junction Table Tests +│ +└── workflows/ ← Workflow JSON-Definitionen + └── README.md ← Workflow-Befehle +``` + +--- + +## 📖 Dokumentations-Kategorien + +### 1️⃣ Entwickler-Handbuch + +#### [docs/ESPOCRM_BEST_PRACTICES.md](docs/ESPOCRM_BEST_PRACTICES.md) ⭐ +**Das Hauptdokument - Start hier!** + +**Inhalt:** +- ✅ Projekt-Übersicht & System-Architektur +- ✅ Architektur-Prinzipien (Clean Code, 3-Schichten) +- ✅ Entity-Entwicklung (Templates, Naming, i18n) +- ✅ Relationship-Patterns (One-to-Many, Many-to-Many, Junction) +- ✅ API-Entwicklung (REST, Custom Endpoints) +- ✅ Workflow-Management +- ✅ Testing & Validierung +- ✅ Fehlerbehandlung & Troubleshooting +- ✅ Deployment-Prozess + +**Wann verwenden:** +- Neuen AI Agent briefen +- Entity erstellen +- Relationship implementieren +- API-Endpoint entwickeln +- Fehler debuggen + +--- + +### 2️⃣ Spezial-Themen + +#### [docs/TESTERGEBNISSE_JUNCTION_TABLE.md](docs/TESTERGEBNISSE_JUNCTION_TABLE.md) +**Junction Tables mit additionalColumns** + +**Inhalt:** +- Many-to-Many Relationships mit Zusatzfeldern +- Junction Entity als API-Endpoint +- API-CRUD Operationen +- Vollständige Code-Beispiele +- ⚠️ UI-Panel Warnung (405 Fehler) + +**Wann verwenden:** +- Many-to-Many mit Zusatzfeldern implementieren +- Junction Entity API nutzen +- additionalColumns verstehen + +--- + +#### [docs/ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md](docs/ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md) +**Puls-System (CPuls) Spezifikation** + +**Inhalt:** +- Posteingangs-System mit KI-Analyse +- Team-basierte Dokumenten-Workflows +- First-Read-Closes Prinzip +- Entity-Definitionen CPuls, CPulsTeamZuordnung +- Middleware-Architektur + +**Wann verwenden:** +- CPuls-Entity weiterentwickeln +- Dokumenten-Workflow verstehen +- KI-Integration planen + +--- + +### 3️⃣ Architektur & Struktur + +#### [README.md](README.md) +**Custom Actions - Implementierungsprinzip** + +**Inhalt:** +- Drei-Schichten-Architektur +- Custom Button Actions Blueprint +- Entity-Erstellung mit Relationen +- Code-Templates +- Sicherheit & ACL + +**Wann verwenden:** +- Custom Button Action erstellen +- Controller/Service Pattern verstehen +- Architektur-Overview benötigen + +--- + +#### [CUSTOM_DIRECTORY.md](CUSTOM_DIRECTORY.md) +**Verzeichnisstruktur-Übersicht** + +**Inhalt:** +- Vollständige custom/ Struktur +- Backend (Espo/Custom/) +- Frontend (client/custom/) +- Metadata-Organisation +- Scripts & Workflows + +**Wann verwenden:** +- Datei-Platzierung nachschlagen +- Verzeichnis-Organisation verstehen +- Neue Dateien korrekt anlegen + +--- + +### 4️⃣ Tool-Dokumentation + +#### [docs/tools/QUICKSTART.md](docs/tools/QUICKSTART.md) +**5-Minuten Quick Start** + +```bash +python3 custom/scripts/validate_and_rebuild.py +``` + +--- + +#### [docs/tools/VALIDATION_TOOLS.md](docs/tools/VALIDATION_TOOLS.md) +**Validierungs-Tools Details** +- PHP-CLI (php -l) +- CSSLint +- JSHint +- Integration + +--- + +#### [docs/tools/E2E_TESTS_README.md](docs/tools/E2E_TESTS_README.md) +**End-to-End Test Framework** +- CRUD-Tests +- Relationship-Tests +- Konfiguration + +--- + +#### [docs/tools/KI_OVERVIEW_README.md](docs/tools/KI_OVERVIEW_README.md) +**KI-Projekt-Übersicht Tool** + +```bash +python3 custom/scripts/ki_project_overview.py > /tmp/project-overview.txt +``` + +--- + +### 5️⃣ Workflow-Management + +#### [docs/workflows/README.md](docs/workflows/README.md) +**Workflow-Format & Management** + +**Befehle:** +```bash +# Liste +php custom/scripts/workflow_manager.php list + +# Import +php custom/scripts/workflow_manager.php import custom/workflows/my-workflow.json + +# Export +php custom/scripts/workflow_manager.php export +``` + +--- + +## 🛠️ Wichtigste Tools + +| Tool | Zweck | Befehl | +|------|-------|--------| +| **validate_and_rebuild.py** | 🎯 Validierung + Rebuild + E2E + Fehlerlog | `python3 custom/scripts/validate_and_rebuild.py` | +| **ki_project_overview.py** | 📊 Projekt-Analyse für AI | `python3 custom/scripts/ki_project_overview.py` | +| **e2e_tests.py** | 🧪 End-to-End CRUD Tests | `python3 custom/scripts/e2e_tests.py` | + +**NEU in validate_and_rebuild.py:** +- ✅ Automatische Fehlerlog-Analyse bei Rebuild-Fehlern +- ✅ Zeigt letzte 50 Log-Zeilen +- ✅ Filtert ERROR/WARNING/EXCEPTION +- ✅ Gibt Log-File-Pfad aus + +--- + +## 🎓 Typische Workflows + +### 1. Neuen AI Agent briefen + +```bash +# 1. Hauptdokumentation lesen +cat custom/docs/ESPOCRM_BEST_PRACTICES.md + +# 2. Aktuellen Projekt-Status holen +python3 custom/scripts/ki_project_overview.py > /tmp/project-overview.txt + +# 3. Dokumentations-Navigation +cat custom/docs/README.md +``` + +--- + +### 2. Neue Entity entwickeln + +```bash +# 1. Template nachschlagen +cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 50 "Entity Definition Template" + +# 2. Entity-Dateien erstellen (entityDefs, scopes, i18n) + +# 3. Validierung + Rebuild +python3 custom/scripts/validate_and_rebuild.py +``` + +--- + +### 3. Relationship implementieren + +```bash +# 1. Pattern nachschlagen +cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 100 "Relationship-Patterns" + +# 2. Links konfigurieren + +# 3. Validierung (prüft bidirektionale Konsistenz) +python3 custom/scripts/validate_and_rebuild.py +``` + +--- + +### 4. Junction Table mit additionalColumns + +```bash +# 1. Vollständige Anleitung +cat custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md + +# 2. Implementierung (Entity + Controller + Service) + +# 3. Validierung +python3 custom/scripts/validate_and_rebuild.py +``` + +--- + +### 5. Fehler debuggen + +```bash +# 1. Validierung ausführen (zeigt automatisch Fehlerlog) +python3 custom/scripts/validate_and_rebuild.py + +# 2. Troubleshooting Guide +cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 200 "Troubleshooting" +``` + +--- + +## 🆘 Support & Hilfe + +### Bei Problemen: + +1. **Fehlerlog-Analyse:** + ```bash + python3 custom/scripts/validate_and_rebuild.py + # → Zeigt automatisch Fehlerlog bei Rebuild-Fehlern + ``` + +2. **Troubleshooting Guide:** + ```bash + cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 300 "Troubleshooting" + ``` + +3. **Häufige Fehler:** + - Layout `false` → `{}` ändern + - i18n fehlt → beide Sprachen (de_DE + en_US) anlegen + - Relationship kaputt → bidirektional prüfen (foreign) + - ACL 403 → Rechte in Admin UI setzen + - 405 Fehler → Keine additionalColumns in UI-Panels! + +--- + +## 📊 System-Info + +- **EspoCRM Version:** 9.3.2 +- **PHP Version:** 8.2.30 +- **Database:** MariaDB 12.2.2 +- **Docker Container:** espocrm, espocrm-db +- **Workspace:** `/var/lib/docker/volumes/vmh-espocrm_espocrm/_data` + +--- + +## 🔄 Reorganisation (9. März 2026) + +**Änderungen:** +- ✅ Alle Dokumentation zentralisiert in `custom/docs/` +- ✅ Tool-Dokumentation in `custom/docs/tools/` +- ✅ Workflow-Dokumentation in `custom/docs/workflows/` +- ✅ Neue Hauptdokumentation: `ESPOCRM_BEST_PRACTICES.md` +- ✅ Test-Scripts organisiert in `custom/scripts/junctiontabletests/` +- ✅ validate_and_rebuild.py erweitert um automatische Fehlerlog-Ausgabe + +**Migration:** +- `scripts/KI_OVERVIEW_README.md` → `docs/tools/` +- `scripts/VALIDATION_TOOLS.md` → `docs/tools/` +- `scripts/E2E_TESTS_README.md` → `docs/tools/` +- `scripts/QUICKSTART.md` → `docs/tools/` +- `scripts/VALIDATOR_README.md` → `docs/tools/` +- `workflows/README.md` → `docs/workflows/` +- `TESTERGEBNISSE_JUNCTION_TABLE.md` → `docs/` +- `ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md` → `docs/` + +--- + +**Letzte Aktualisierung:** 9. März 2026 + +**Für Fragen:** Siehe `custom/docs/ESPOCRM_BEST_PRACTICES.md` diff --git a/custom/ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md b/custom/docs/ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md similarity index 100% rename from custom/ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md rename to custom/docs/ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md diff --git a/custom/docs/ESPOCRM_BEST_PRACTICES.md b/custom/docs/ESPOCRM_BEST_PRACTICES.md new file mode 100644 index 00000000..09d5b0f8 --- /dev/null +++ b/custom/docs/ESPOCRM_BEST_PRACTICES.md @@ -0,0 +1,1087 @@ +# EspoCRM Best Practices & Entwicklungsrichtlinien + +**Version:** 2.0 +**Datum:** 9. März 2026 +**Zielgruppe:** AI Code Agents & Entwickler + +--- + +## 📋 Inhaltsverzeichnis + +1. [Projekt-Übersicht](#projekt-übersicht) +2. [Architektur-Prinzipien](#architektur-prinzipien) +3. [Entity-Entwicklung](#entity-entwicklung) +4. [Relationship-Patterns](#relationship-patterns) +5. [API-Entwicklung](#api-entwicklung) +6. [Workflow-Management](#workflow-management) +7. [Testing & Validierung](#testing--validierung) +8. [Fehlerbehandlung](#fehlerbehandlung) +9. [Deployment-Prozess](#deployment-prozess) +10. [Troubleshooting](#troubleshooting) + +--- + +## Projekt-Übersicht + +### System-Architektur + +``` +EspoCRM 9.3.2 +├── PHP 8.2.30 +├── MariaDB 12.2.2 +├── Docker Container: espocrm, espocrm-db +└── Workspace: /var/lib/docker/volumes/vmh-espocrm_espocrm/_data +``` + +### Verzeichnisstruktur + +``` +custom/ +├── Espo/Custom/ # Backend-Code +│ ├── Controllers/ # REST API Endpoints +│ ├── Services/ # Business Logic +│ ├── Repositories/ # Data Access Layer +│ ├── Hooks/ # Entity Lifecycle Hooks +│ └── Resources/ +│ ├── metadata/ # Entity & Field Definitionen +│ │ ├── entityDefs/ # Entity-Konfiguration +│ │ ├── clientDefs/ # Frontend-Konfiguration +│ │ ├── scopes/ # Entity-Scopes +│ │ └── formula/ # Formula Scripts +│ ├── layouts/ # UI-Layouts +│ └── i18n/ # Übersetzungen (de_DE, en_US) +├── scripts/ # Entwicklungs-Tools +│ ├── validate_and_rebuild.py # Haupt-Validierungs-Tool +│ ├── e2e_tests.py # End-to-End Tests +│ ├── ki_project_overview.py # Projekt-Analyse für AI +│ └── junctiontabletests/ # Junction Table Tests +├── docs/ # Dokumentation (NEU) +│ ├── ESPOCRM_BEST_PRACTICES.md # Dieses Dokument +│ ├── tools/ # Tool-Dokumentation +│ └── workflows/ # Workflow-Dokumentation +└── workflows/ # Workflow JSON-Definitions + +client/custom/ # Frontend-Code +├── src/ # JavaScript Modules +├── css/ # Custom Styles +└── res/ # Resources +``` + +--- + +## Architektur-Prinzipien + +### 1. Separation of Concerns + +**EspoCRM = Data Layer** +- Speichert Entities +- Stellt UI bereit +- Validiert Daten +- Bietet REST API + +**Middleware = Business Logic** +- KI-Analyse +- Team-Zuweisung +- Komplexe Workflows +- Externe Integrationen + +### 2. Drei-Schichten-Architektur + +``` +┌─────────────────────────────────────────┐ +│ FRONTEND (clientDefs, Layouts) │ +│ • User Interface │ +│ • JavaScript Actions │ +└────────────────┬────────────────────────┘ + │ AJAX/REST +┌────────────────▼────────────────────────┐ +│ CONTROLLER (Controllers/) │ +│ • Request Validation │ +│ • ACL Checks │ +└────────────────┬────────────────────────┘ + │ Service Call +┌────────────────▼────────────────────────┐ +│ SERVICE (Services/) │ +│ • Business Logic │ +│ • Entity Manager │ +└────────────────┬────────────────────────┘ + │ Repository +┌────────────────▼────────────────────────┐ +│ REPOSITORY (Repositories/) │ +│ • Data Access │ +│ • Relationships │ +└─────────────────────────────────────────┘ +``` + +### 3. Clean Code Principles + +**DO:** +- ✅ Nutze sprechende Variablennamen +- ✅ Schreibe kleine, fokussierte Funktionen +- ✅ Kommentiere komplexe Business-Logik +- ✅ Verwende Type Hints (PHP 8.2+) +- ✅ Folge PSR-12 Coding Standard + +**DON'T:** +- ❌ Keine komplexe Logik in Hooks +- ❌ Keine direkten SQL-Queries (nutze EntityManager) +- ❌ Keine hard-coded Werte (nutze Config) +- ❌ Keine redundanten Includes +- ❌ Keine ungenutzten Imports + +--- + +## Entity-Entwicklung + +### Entity-Naming Convention + +**Pattern:** `C{EntityName}` für Custom Entities + +**Beispiele:** +- `CMietobjekt` - Mietobjekte +- `CVmhMietverhltnis` - Mietverhältnisse (VMH = Vermieter Helden) +- `CKuendigung` - Kündigungen +- `CAICollections` - AI Collections + +### Entity Definition Template + +**Datei:** `custom/Espo/Custom/Resources/metadata/entityDefs/{EntityName}.json` + +```json +{ + "fields": { + "name": { + "type": "varchar", + "required": true, + "maxLength": 255, + "trim": true, + "isCustom": true, + "tooltip": true + }, + "status": { + "type": "enum", + "options": ["Neu", "In Bearbeitung", "Abgeschlossen"], + "default": "Neu", + "required": true, + "isCustom": true, + "style": { + "Neu": "primary", + "In Bearbeitung": "warning", + "Abgeschlossen": "success" + } + }, + "description": { + "type": "text", + "rows": 10, + "isCustom": true, + "tooltip": true + }, + "amount": { + "type": "currency", + "isCustom": true, + "audited": true + }, + "dueDate": { + "type": "date", + "isCustom": true, + "audited": true + } + }, + "links": { + "parent": { + "type": "belongsToParent", + "entityList": ["CVmhRumungsklage", "CMietinkasso"] + }, + "createdBy": { + "type": "belongsTo", + "entity": "User" + }, + "modifiedBy": { + "type": "belongsTo", + "entity": "User" + } + } +} +``` + +### Scope Definition + +**Datei:** `custom/Espo/Custom/Resources/metadata/scopes/{EntityName}.json` + +```json +{ + "entity": true, + "type": "Base", + "module": "Custom", + "object": true, + "isCustom": true, + "tab": true, + "acl": true, + "stream": true, + "disabled": false, + "customizable": true, + "importable": true, + "notifications": true, + "calendar": false +} +``` + +**Wichtige Flags:** +- `tab: true` - Zeigt Entity in Navigation +- `acl: true` - ACL-System aktiv +- `stream: true` - Stream/Activity Feed +- `calendar: true` - Für Entities mit Datum-Feldern + +### i18n (Internationalisierung) + +**KRITISCH:** Immer BEIDE Sprachen pflegen! + +**Datei:** `custom/Espo/Custom/Resources/i18n/de_DE/{EntityName}.json` + +```json +{ + "labels": { + "Create {EntityName}": "{EntityName} erstellen", + "{EntityName}": "{EntityName}", + "name": "Name", + "status": "Status", + "description": "Beschreibung" + }, + "fields": { + "name": "Name", + "status": "Status", + "description": "Beschreibung", + "amount": "Betrag", + "dueDate": "Fälligkeitsdatum" + }, + "links": { + "parent": "Übergeordnet", + "relatedEntity": "Verknüpfte Entity" + }, + "options": { + "status": { + "Neu": "Neu", + "In Bearbeitung": "In Bearbeitung", + "Abgeschlossen": "Abgeschlossen" + } + }, + "tooltips": { + "name": "Eindeutiger Name des Datensatzes", + "description": "Detaillierte Beschreibung" + } +} +``` + +**Datei:** `custom/Espo/Custom/Resources/i18n/en_US/{EntityName}.json` + +```json +{ + "labels": { + "Create {EntityName}": "Create {EntityName}", + "{EntityName}": "{EntityName}" + }, + "fields": { + "name": "Name", + "status": "Status", + "description": "Description", + "amount": "Amount", + "dueDate": "Due Date" + }, + "links": { + "parent": "Parent", + "relatedEntity": "Related Entity" + }, + "options": { + "status": { + "Neu": "New", + "In Bearbeitung": "In Progress", + "Abgeschlossen": "Completed" + } + } +} +``` + +--- + +## Relationship-Patterns + +### 1. One-to-Many (hasMany / belongsTo) + +**Beispiel:** Ein Mietobjekt hat viele Mietverhältnisse + +**Parent Entity (CMietobjekt):** +```json +{ + "links": { + "mietverhltnisse": { + "type": "hasMany", + "entity": "CVmhMietverhltnis", + "foreign": "mietobjekt" + } + } +} +``` + +**Child Entity (CVmhMietverhltnis):** +```json +{ + "fields": { + "mietobjektId": { + "type": "varchar", + "len": 17 + }, + "mietobjektName": { + "type": "varchar" + } + }, + "links": { + "mietobjekt": { + "type": "belongsTo", + "entity": "CMietobjekt", + "foreign": "mietverhltnisse" + } + } +} +``` + +### 2. Many-to-Many (hasMany mit relationName) + +**Beispiel:** Dokumente ↔ AI Collections + +**Entity 1 (CDokumente):** +```json +{ + "links": { + "cAICollections": { + "type": "hasMany", + "entity": "CAICollections", + "foreign": "cDokumente", + "relationName": "cAICollectionCDokumente" + } + } +} +``` + +**Entity 2 (CAICollections):** +```json +{ + "links": { + "cDokumente": { + "type": "hasMany", + "entity": "CDokumente", + "foreign": "cAICollections", + "relationName": "cAICollectionCDokumente" + } + } +} +``` + +**Wichtig:** `relationName` muss identisch sein! + +### 3. Many-to-Many mit additionalColumns (Junction Entity) + +**Seit EspoCRM 6.0:** Junction-Tabellen werden automatisch als Entities verfügbar! + +**Entity Definition:** +```json +{ + "links": { + "cDokumente": { + "type": "hasMany", + "entity": "CDokumente", + "foreign": "cAICollections", + "relationName": "cAICollectionCDokumente", + "additionalColumns": { + "syncId": { + "type": "varchar", + "len": 255 + } + } + } + } +} +``` + +**Junction Entity (CAICollectionCDokumente):** + +**entityDefs/CAICollectionCDokumente.json:** +```json +{ + "fields": { + "id": { + "type": "id", + "dbType": "bigint", + "autoincrement": true + }, + "cAICollections": { + "type": "link" + }, + "cAICollectionsId": { + "type": "varchar", + "len": 17, + "index": true + }, + "cDokumente": { + "type": "link" + }, + "cDokumenteId": { + "type": "varchar", + "len": 17, + "index": true + }, + "syncId": { + "type": "varchar", + "len": 255, + "isCustom": true + }, + "deleted": { + "type": "bool", + "default": false + } + }, + "links": { + "cAICollections": { + "type": "belongsTo", + "entity": "CAICollections" + }, + "cDokumente": { + "type": "belongsTo", + "entity": "CDokumente" + } + } +} +``` + +**scopes/CAICollectionCDokumente.json:** +```json +{ + "entity": true, + "type": "Base", + "module": "Custom", + "object": true, + "isCustom": true, + "tab": false, + "acl": true, + "disabled": false +} +``` + +**Controller & Service:** +```php +getParsedBody(); + $id = $data->id ?? null; + + if (!$id) { + throw new BadRequest('ID is required'); + } + + $result = $this->getRecordService()->doSomething($id, $data); + + return [ + 'success' => true, + 'data' => $result + ]; + } + + /** + * Custom GET Action: GET /api/v1/CMyEntity/{id}/customData + */ + public function getActionCustomData(Request $request): array + { + $id = $request->getRouteParam('id'); + + $data = $this->getRecordService()->getCustomData($id); + + return [ + 'data' => $data + ]; + } +} +``` + +**2. Service Logic:** + +**Datei:** `custom/Espo/Custom/Services/{EntityName}.php` + +```php +getAcl()->checkEntityEdit($this->entityType)) { + throw new Forbidden(); + } + + // Load Entity + $entity = $this->getEntityManager()->getEntity($this->entityType, $id); + if (!$entity) { + throw new NotFound(); + } + + // Business Logic + $entity->set('status', 'In Bearbeitung'); + $this->getEntityManager()->saveEntity($entity); + + // Return Result + return [ + 'id' => $entity->getId(), + 'status' => $entity->get('status') + ]; + } + + public function getCustomData(string $id): array + { + $entity = $this->getEntityManager()->getEntity($this->entityType, $id); + if (!$entity) { + throw new NotFound(); + } + + // Complex data aggregation + $relatedData = $this->getRelatedData($entity); + + return [ + 'entity' => $entity->getValueMap(), + 'related' => $relatedData + ]; + } +} +``` + +### API Authentication + +**API Key Header:** +```bash +curl -X GET "https://crm.example.com/api/v1/CMyEntity" \ + -H "X-Api-Key: your-api-key-here" +``` + +**Test API Keys:** +- `marvin`: `e53def10eea27b92a6cd00f40a3e09a4` +- `dev-test`: `2b0747ca34d15032aa233ae043cc61bc` + +--- + +## Workflow-Management + +### Workflow-Dateien + +**Verzeichnis:** `custom/workflows/` + +**Format:** JSON (Simple Workflow oder BPM Flowchart) + +### Simple Workflow Beispiel + +```json +{ + "type": "simple", + "name": "auto-assign-new-entity", + "entity_type": "CMyEntity", + "trigger_type": "afterRecordCreated", + "is_active": true, + "description": "Auto-assign new records to team", + "conditions_all": [ + { + "type": "isEmpty", + "attribute": "assignedUserId" + } + ], + "actions": [ + { + "type": "applyAssignmentRule", + "targetTeamId": "team-id-here" + }, + { + "type": "sendEmail", + "to": "assignedUser", + "emailTemplateId": "template-id" + } + ] +} +``` + +### Workflow Import/Export + +```bash +# Alle Workflows exportieren +php custom/scripts/workflow_manager.php export + +# Workflow importieren +php custom/scripts/workflow_manager.php import custom/workflows/my-workflow.json + +# Workflows auflisten +php custom/scripts/workflow_manager.php list +``` + +--- + +## Testing & Validierung + +### Validierungs-Tool + +**Haupt-Tool:** `custom/scripts/validate_and_rebuild.py` + +```bash +# Vollständige Validierung + Rebuild +python3 custom/scripts/validate_and_rebuild.py + +# Nur Validierung (kein Rebuild) +python3 custom/scripts/validate_and_rebuild.py --dry-run + +# Mit E2E Tests überspringen +python3 custom/scripts/validate_and_rebuild.py --skip-e2e +``` + +**Das Tool prüft:** +1. ✅ JSON-Syntax aller Custom-Dateien +2. ✅ Relationship-Konsistenz (bidirektionale Links) +3. ✅ Formula-Script Platzierung +4. ✅ i18n-Vollständigkeit (de_DE + en_US) +5. ✅ Layout-Struktur (bottomPanelsDetail, detail.json) +6. ✅ Dateirechte (www-data:www-data) +7. ✅ CSS-Validierung (csslint) +8. ✅ JavaScript-Validierung (jshint) +9. ✅ PHP-Syntax (php -l) +10. ✅ EspoCRM Rebuild +11. ✅ E2E-Tests (CRUD-Operationen) + +**Bei Fehlern:** Automatische Fehlerlog-Analyse der letzten 50 Log-Zeilen! + +### End-to-End Tests + +**Tool:** `custom/scripts/e2e_tests.py` + +```bash +# E2E Tests ausführen +python3 custom/scripts/e2e_tests.py +``` + +**Tests:** +- CRUD für alle Custom Entities +- Relationship-Verknüpfungen +- ACL-Prüfungen + +### Manuelle Tests + +**Checkliste:** +- [ ] Entity in UI sichtbar? +- [ ] Felder editierbar? +- [ ] Relationships funktionieren? +- [ ] Formulas triggern korrekt? +- [ ] Workflows aktiv? +- [ ] API-Endpoints erreichbar? +- [ ] ACL-Regeln greifen? + +--- + +## Fehlerbehandlung + +### Log-Files + +**Verzeichnis:** `data/logs/` + +**Haupt-Logfile:** `espo-{YYYY-MM-DD}.log` + +```bash +# Letzte Fehler anzeigen +tail -50 data/logs/espo-$(date +%Y-%m-%d).log | grep -i error + +# Live-Monitoring +tail -f data/logs/espo-$(date +%Y-%m-%d).log +``` + +### Häufige Fehler + +#### 1. Layout-Fehler: "false" statt "{}" + +**Problem:** EspoCRM 7.x+ erfordert `{}` statt `false` als Platzhalter + +**Falsch:** +```json +{ + "rows": [ + [ + {"name": "field1"}, + false + ] + ] +} +``` + +**Richtig:** +```json +{ + "rows": [ + [ + {"name": "field1"}, + {} + ] + ] +} +``` + +#### 2. Relationship nicht bidirektional + +**Problem:** `foreign` zeigt nicht zurück + +**Falsch:** +```json +// Entity A +"links": { + "entityB": { + "type": "hasMany", + "entity": "EntityB", + "foreign": "wrongName" // ❌ + } +} + +// Entity B +"links": { + "entityA": { + "type": "belongsTo", + "entity": "EntityA", + "foreign": "entityB" + } +} +``` + +**Richtig:** +```json +// Entity A +"links": { + "entityB": { + "type": "hasMany", + "entity": "EntityB", + "foreign": "entityA" // ✅ Zeigt auf Link-Namen in B + } +} + +// Entity B +"links": { + "entityA": { + "type": "belongsTo", + "entity": "EntityA", + "foreign": "entityB" // ✅ Zeigt auf Link-Namen in A + } +} +``` + +#### 3. i18n fehlt für en_US + +**Problem:** Nur de_DE vorhanden, en_US fehlt + +**Lösung:** IMMER beide Sprachen pflegen! en_US ist Fallback. + +#### 4. Dateirechte falsch + +**Problem:** Files gehören root statt www-data + +**Lösung:** Automatisch via validate_and_rebuild.py oder manuell: +```bash +sudo chown -R www-data:www-data custom/ +sudo find custom/ -type f -exec chmod 664 {} \; +sudo find custom/ -type d -exec chmod 775 {} \; +``` + +#### 5. ACL: 403 Forbidden + +**Problem:** Role hat keine Rechte auf Entity + +**Lösung:** ACL in Admin UI oder via SQL: +```sql +UPDATE role +SET data = JSON_SET(data, + '$.table.CMyEntity', + JSON_OBJECT('create', 'yes', 'read', 'all', 'edit', 'all', 'delete', 'all') +) +WHERE name = 'RoleName'; +``` + +--- + +## Deployment-Prozess + +### Standard-Workflow + +```bash +# 1. Code-Änderungen durchführen +vim custom/Espo/Custom/Resources/metadata/entityDefs/CMyEntity.json + +# 2. Validierung + Rebuild +python3 custom/scripts/validate_and_rebuild.py + +# 3. Bei Erfolg: Commit +git add custom/ +git commit -m "feat: Add CMyEntity with custom fields" +git push +``` + +### Quick Rebuild (nach kleinen Änderungen) + +```bash +docker exec espocrm php command.php clear-cache +docker exec espocrm php command.php rebuild +``` + +### Nach Änderungen an Relationships + +**IMMER:** +1. Cache löschen +2. Rebuild ausführen +3. Browser-Cache löschen (Ctrl+F5) + +--- + +## Troubleshooting + +### Rebuild schlägt fehl + +**1. Logs prüfen:** +```bash +python3 custom/scripts/validate_and_rebuild.py +# → Zeigt automatisch Fehlerlog-Analyse +``` + +**2. Manuell Logs checken:** +```bash +tail -100 data/logs/espo-$(date +%Y-%m-%d).log +``` + +**3. PHP-Fehler:** +```bash +docker exec espocrm php -l custom/Espo/Custom/Controllers/MyController.php +``` + +### Entity nicht sichtbar + +**Checklist:** +- [ ] `tab: true` in scopes? +- [ ] `disabled: false` in scopes? +- [ ] ACL-Rechte für Role? +- [ ] Cache gelöscht? +- [ ] Rebuild durchgeführt? + +### Relationship funktioniert nicht + +**Checklist:** +- [ ] Bidirektional konfiguriert? +- [ ] `foreign` zeigt korrekt zurück? +- [ ] `relationName` identisch (bei M2M)? +- [ ] Rebuild durchgeführt? + +### API gibt 404 + +**Checklist:** +- [ ] Controller existiert? +- [ ] Service existiert? +- [ ] Action-Methode korrekt benannt? (postAction..., getAction...) +- [ ] ACL-Rechte? + +### Formula triggert nicht + +**Checklist:** +- [ ] In `metadata/formula/` statt entityDefs? +- [ ] Syntax korrekt? +- [ ] Rebuild durchgeführt? + +--- + +## Projekt-spezifische Entities + +### Übersicht + +1. **CMietobjekt** - Mietobjekte (Wohnungen/Häuser) +2. **CVmhMietverhltnis** - Mietverhältnisse +3. **CKuendigung** - Kündigungen +4. **CBeteiligte** - Beteiligte Personen +5. **CMietinkasso** - Mietinkasso-Verfahren +6. **CVmhRumungsklage** - Räumungsklagen +7. **CDokumente** - Dokumente +8. **CPuls** - Puls-System (Entwicklungen) +9. **CAICollections** - AI Collections + +### Entity-Graph + +``` +CMietobjekt + ├── CVmhMietverhltnis (hasMany) + │ ├── CKuendigung (hasMany) + │ │ └── CVmhRumungsklage (hasOne) + │ ├── CMietinkasso (hasMany) + │ └── CBeteiligte (hasMany) + └── Contact (hasMany) + +CDokumente + ├── parent → [CVmhRumungsklage, CMietinkasso, CKuendigung] + └── CAICollections (hasMany via Junction) + └── CPuls (hasMany) +``` + +--- + +## Tools & Scripts + +### Übersicht + +| Tool | Zweck | Ausführung | +|------|-------|-----------| +| validate_and_rebuild.py | Validierung + Rebuild | `python3 custom/scripts/validate_and_rebuild.py` | +| e2e_tests.py | End-to-End Tests | `python3 custom/scripts/e2e_tests.py` | +| ki_project_overview.py | Projekt-Analyse für AI | `python3 custom/scripts/ki_project_overview.py` | +| workflow_manager.php | Workflow-Verwaltung | `php custom/scripts/workflow_manager.php list` | + +### KI-Projekt-Übersicht + +**Für AI Code Agents:** +```bash +python3 custom/scripts/ki_project_overview.py > /tmp/project-overview.txt +# → Gibt vollständigen Projekt-Status für AI aus +``` + +--- + +## Ressourcen + +### Dokumentation + +- **EspoCRM Docs:** https://docs.espocrm.com/ +- **API Reference:** https://docs.espocrm.com/development/api/ +- **Formula Functions:** https://docs.espocrm.com/administration/formula/ + +### Projekt-Dokumentation + +- `custom/docs/ESPOCRM_BEST_PRACTICES.md` - Dieses Dokument +- `custom/scripts/QUICKSTART.md` - Quick Start Guide +- `custom/scripts/VALIDATION_TOOLS.md` - Validierungs-Tools +- `custom/scripts/E2E_TESTS_README.md` - E2E Tests +- `custom/README.md` - Custom Actions Blueprint +- `custom/TESTERGEBNISSE_JUNCTION_TABLE.md` - Junction Table Implementation + +--- + +## Glossar + +**ACL** - Access Control List (Zugriffsrechte) +**Entity** - Datenmodell (z.B. CMietobjekt) +**Link** - Relationship zwischen Entities +**Junction Table** - Verbindungstabelle für Many-to-Many +**Formula** - Berechnete Felder oder Automation-Scripts +**Scope** - Entity-Konfiguration (Tab, ACL, etc.) +**Stream** - Activity Feed einer Entity +**Hook** - Lifecycle-Event-Handler +**Service** - Business Logic Layer +**Controller** - API Request Handler +**Repository** - Data Access Layer + +--- + +**Ende der Best Practices Dokumentation** + +Für spezifische Fragen oder Updates: Siehe `/custom/docs/` Verzeichnis. diff --git a/custom/docs/README.md b/custom/docs/README.md new file mode 100644 index 00000000..ef35fae4 --- /dev/null +++ b/custom/docs/README.md @@ -0,0 +1,319 @@ +# EspoCRM Custom Development - Dokumentation + +**Zentrale Dokumentation für EspoCRM-Entwicklung mit KI-Support** + +--- + +## 📂 Struktur + +``` +custom/docs/ +├── README.md # Diese Datei +├── ESPOCRM_BEST_PRACTICES.md # ⭐ HAUPTDOKUMENTATION +├── TESTERGEBNISSE_JUNCTION_TABLE.md # Junction Table Implementation +├── ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md # Puls-System Spezifikation +├── tools/ # Tool-Dokumentation +│ ├── QUICKSTART.md # Quick Start Guide +│ ├── VALIDATION_TOOLS.md # Validierungs-Tools +│ ├── E2E_TESTS_README.md # End-to-End Tests +│ ├── KI_OVERVIEW_README.md # KI-Projekt-Übersicht +│ └── VALIDATOR_README.md # Validator Details +└── workflows/ # Workflow-Dokumentation + └── README.md # Workflow-Format & Import/Export +``` + +--- + +## 🚀 Für AI Code Agents - HIER STARTEN! + +### 1. Lies zuerst: ESPOCRM_BEST_PRACTICES.md + +**Das Hauptdokument enthält:** +- ✅ Projekt-Übersicht & Architektur +- ✅ Entity-Entwicklung (Naming, Templates, i18n) +- ✅ Relationship-Patterns (One-to-Many, Many-to-Many, Junction Tables) +- ✅ API-Entwicklung (REST Endpoints, Custom Actions) +- ✅ Workflow-Management +- ✅ Testing & Validierung +- ✅ Fehlerbehandlung & Troubleshooting +- ✅ Deployment-Prozess +- ✅ Projekt-spezifische Entities + +**Befehl:** +```bash +cat custom/docs/ESPOCRM_BEST_PRACTICES.md +``` + +### 2. Projekt-Analyse abrufen + +**Für umfassenden aktuellen Projekt-Status:** +```bash +python3 custom/scripts/ki_project_overview.py > /tmp/project-overview.txt +cat /tmp/project-overview.txt +``` + +**Output:** Alle Entities, Relationships, Custom Code, Workflows + +### 3. Validierung & Rebuild ausführen + +**Vor jeder Entwicklung:** +```bash +python3 custom/scripts/validate_and_rebuild.py +``` + +**Das Tool führt automatisch durch:** +1. JSON-Syntax Check +2. Relationship-Validierung +3. i18n-Vollständigkeit +4. Layout-Struktur +5. Dateirechte +6. CSS/JS/PHP Validierung +7. EspoCRM Rebuild +8. E2E-Tests +9. **NEU:** Automatische Fehlerlog-Analyse bei Rebuild-Fehlern! + +--- + +## 📖 Dokumentations-Guide + +### Hauptdokumentation + +#### ESPOCRM_BEST_PRACTICES.md +**Vollständiges Entwickler-Handbuch** +- Architektur-Prinzipien +- Entity-Development mit Templates +- Relationship-Patterns inkl. Junction Tables +- API-Entwicklung (Controller, Service, REST) +- Workflow-Management +- Testing (Validierung, E2E) +- Troubleshooting & Fehlerbehandlung + +**Verwende diese Datei für:** +- Neuen Code-Agent briefen +- Entwicklungsstandards nachschlagen +- Entity-Templates kopieren +- Fehler debuggen + +#### TESTERGEBNISSE_JUNCTION_TABLE.md +**Junction Table Implementation Guide** +- Many-to-Many mit additionalColumns +- Junction Entity als API-Endpoint +- Vollständige Code-Beispiele +- API-Nutzung (CRUD, Filter, Sort) + +**Verwende diese Datei für:** +- Many-to-Many Beziehungen mit Zusatzfeldern +- API-only Access Pattern +- Junction Entity Implementation + +#### ENTWICKLUNGSPLAN_ENTWICKLUNGEN.md +**Puls-System (CPuls) Spezifikation** +- Posteingangs-System mit KI-Analyse +- Team-basierte Dokumenten-Workflows +- First-Read-Closes Prinzip +- Entity-Definitionen und Beziehungen + +**Verwende diese Datei für:** +- CPuls-Entity Weiterentwicklung +- Dokumenten-Workflow-Logik +- KI-Integration-Patterns + +--- + +## 🛠️ Tool-Dokumentation + +### tools/QUICKSTART.md +**5-Minuten Quick Start für Validator** +- Installation bereits fertig +- Verwendung: `python3 custom/scripts/validate_and_rebuild.py` +- Output-Interpretation + +### tools/VALIDATION_TOOLS.md +**Technische Details zu Validierungs-Tools** +- PHP-CLI (php -l) +- CSSLint (csslint) +- JSHint (jshint) +- Integration im Validator + +### tools/E2E_TESTS_README.md +**End-to-End Test Framework** +- CRUD-Tests für Custom Entities +- Relationship-Tests +- Konfiguration & Ausführung + +### tools/KI_OVERVIEW_README.md +**KI-Projekt-Übersicht Tool** +- Automatische Projekt-Analyse +- Output-Format für AI Agents +- Verwendung: `python3 custom/scripts/ki_project_overview.py` + +### tools/VALIDATOR_README.md +**Validator Details** +- Alternative zu VALIDATION_TOOLS.md +- Erweiterte Validator-Funktionalität + +--- + +## 📋 Workflow-Dokumentation + +### workflows/README.md +**Workflow-Format & Management** +- Simple Workflow JSON-Format +- BPM Flowchart Format +- Import/Export mit `workflow_manager.php` +- Trigger Types, Actions, Conditions + +**Befehle:** +```bash +# Workflows auflisten +php custom/scripts/workflow_manager.php list + +# Workflow importieren +php custom/scripts/workflow_manager.php import custom/workflows/my-workflow.json + +# Alle Workflows exportieren +php custom/scripts/workflow_manager.php export +``` + +--- + +## 🎯 Typische Workflows + +### Neue Entity entwickeln + +```bash +# 1. Best Practices lesen +cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 50 "Entity Definition Template" + +# 2. Entity-Dateien erstellen (entityDefs, scopes, i18n de_DE + en_US) + +# 3. Validierung + Rebuild +python3 custom/scripts/validate_and_rebuild.py +``` + +### Relationship implementieren + +```bash +# 1. Relationship-Pattern nachschlagen +cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 100 "Relationship-Patterns" + +# 2. Links in beiden Entities konfigurieren + +# 3. Validierung (prüft bidirektionale Konsistenz) +python3 custom/scripts/validate_and_rebuild.py +``` + +### Junction Table mit additionalColumns + +```bash +# 1. Vollständige Anleitung lesen +cat custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md + +# 2. Entity-Definitionen + Junction Entity erstellen + +# 3. Controller & Service für Junction Entity + +# 4. Validierung + Test +python3 custom/scripts/validate_and_rebuild.py +``` + +### Fehler debuggen + +```bash +# 1. Validierung ausführen (zeigt automatisch Fehlerlog bei Rebuild-Fehler) +python3 custom/scripts/validate_and_rebuild.py + +# 2. Manuell Logs prüfen (falls nötig) +tail -100 data/logs/espo-$(date +%Y-%m-%d).log | grep -i error + +# 3. Troubleshooting Guide +cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 200 "Troubleshooting" +``` + +--- + +## 🔧 Entwicklungs-Tools Übersicht + +| Tool | Zweck | Befehl | +|------|-------|--------| +| **validate_and_rebuild.py** | Haupttool: Validierung + Rebuild + E2E | `python3 custom/scripts/validate_and_rebuild.py` | +| **ki_project_overview.py** | Projekt-Analyse für AI | `python3 custom/scripts/ki_project_overview.py` | +| **e2e_tests.py** | End-to-End CRUD Tests | `python3 custom/scripts/e2e_tests.py` | +| **workflow_manager.php** | Workflow Import/Export | `php custom/scripts/workflow_manager.php list` | + +**Alle Tools dokumentiert in:** `custom/docs/tools/` + +--- + +## 📚 Weitere Ressourcen + +### Projekt-spezifische Dokumente + +- `../README.md` - Custom Actions Blueprint +- `../CUSTOM_DIRECTORY.md` - Verzeichnisstruktur-Übersicht + +### EspoCRM Offizielle Docs + +- **Main Docs:** https://docs.espocrm.com/ +- **API Reference:** https://docs.espocrm.com/development/api/ +- **Formula Functions:** https://docs.espocrm.com/administration/formula/ + +--- + +## 🎓 Best Practices Zusammenfassung + +### DO ✅ + +- **IMMER beide Sprachen:** de_DE + en_US (en_US ist Fallback!) +- **Bidirektionale Relationships:** `foreign` muss zurück zeigen +- **Validierung vor Rebuild:** Nutze `validate_and_rebuild.py` +- **Sprechende Namen:** `C{EntityName}` für Custom Entities +- **Clean Code:** Kleine Funktionen, Type Hints, Kommentare +- **Layouts mit {}:** EspoCRM 7.x+ erfordert `{}` statt `false` + +### DON'T ❌ + +- **Keine fehlende i18n:** immer de_DE UND en_US +- **Keine unidirektionalen Links:** immer foreign konfigurieren +- **Keine komplexe Logik in Hooks:** nutze Services +- **Keine direkten SQL-Queries:** nutze EntityManager +- **Keine hard-coded Werte:** nutze Config + +--- + +## 🆘 Support & Troubleshooting + +### Bei Problemen: + +1. **Fehlerlog-Analyse:** + ```bash + python3 custom/scripts/validate_and_rebuild.py + # → Zeigt automatisch Fehler bei Rebuild-Fehlern + ``` + +2. **Troubleshooting Guide:** + ```bash + cat custom/docs/ESPOCRM_BEST_PRACTICES.md | grep -A 300 "Troubleshooting" + ``` + +3. **Häufige Fehler:** + - Layout `false` → `{}` ändern + - i18n fehlt → beide Sprachen anlegen + - Relationship kaputt → bidirektional prüfen + - ACL 403 → Rechte in Admin UI + +--- + +## 📊 System-Info + +- **EspoCRM Version:** 9.3.2 +- **PHP Version:** 8.2.30 +- **Database:** MariaDB 12.2.2 +- **Docker Container:** espocrm, espocrm-db +- **Workspace:** `/var/lib/docker/volumes/vmh-espocrm_espocrm/_data` + +--- + +**Letzte Aktualisierung:** 9. März 2026 + +**Für Fragen oder Updates:** Siehe `custom/docs/ESPOCRM_BEST_PRACTICES.md` diff --git a/custom/TESTERGEBNISSE_JUNCTION_TABLE.md b/custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md similarity index 85% rename from custom/TESTERGEBNISSE_JUNCTION_TABLE.md rename to custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md index f11e46e1..376c8dcb 100644 --- a/custom/TESTERGEBNISSE_JUNCTION_TABLE.md +++ b/custom/docs/TESTERGEBNISSE_JUNCTION_TABLE.md @@ -266,9 +266,21 @@ response = requests.put( | CREATE via API | ✅ | POST mit allen Feldern | | UPDATE via API | ✅ | PUT zum Ändern von syncId | | DELETE via API | ✅ | Standard-DELETE | -| View-Darstellung | ✅* | Möglich, aber manuell konfigurieren | +| View-Darstellung | ❌ | Nicht empfohlen - verursacht 405 Fehler | -*) Benötigt manuelle Layout-Konfiguration im Entity Manager +## ⚠️ UI-Panel Warnung + +**WICHTIG:** additionalColumns sollten NICHT in Standard-Relationship-Panels angezeigt werden! + +**Problem:** +- Standard relationship panels versuchen inline-editing +- Dies führt zu 405 Method Not Allowed Fehlern +- additionalColumns sind nicht kompatibel mit Standard-Panel-Architektur + +**Empfehlung:** +- ✅ Nutze API-only Access Pattern +- ✅ Vollständige CRUD via `/api/v1/CAICollectionCDokumente` +- ❌ NICHT in CDokumente detail view als relationship panel anzeigen ## 🎯 Fazit @@ -280,6 +292,18 @@ Die **Junction-Tabelle mit `additionalColumns` ist vollständig via REST-API nut - ✅ CRUD-Operationen vollständig unterstützt - ✅ `syncId` ist direkt in der Response - ✅ Einfache Integration in externe Systeme +- ✅ API-only Pattern verhindert 405-Fehler + +**Einschränkungen:** +- ⚠️ UI-Darstellung in Standard-Relationship-Panels verursacht 405 Fehler +- ⚠️ additionalColumns nur über Junction-Entity-API zugänglich +- ⚠️ Standard relationship endpoints (z.B. GET /api/v1/CDokumente/{id}/cAICollections) geben additionalColumns NICHT zurück + +**Best Practice:** +1. ✅ Junction Entity als API-Endpoint nutzen (`/api/v1/CAICollectionCDokumente`) +2. ✅ Keine UI-Panels für Junction-Relationships mit additionalColumns +3. ✅ API-Integration für externe Systeme (Middleware, KI, etc.) +4. ✅ Bei Bedarf: Separate Management-UI für Junction Entity (ohne Relationship-Panel) **Wichtig:** 1. Controller und Service erstellen @@ -287,6 +311,7 @@ Die **Junction-Tabelle mit `additionalColumns` ist vollständig via REST-API nut 3. Entity-Definition mit korrekten Feldtypen 4. ACL-Rechte für die Junction-Entity setzen 5. Cache löschen und rebuild +6. **NICHT** als Relationship-Panel in UI anzeigen (→ 405 Fehler) ## 📁 Dateien @@ -367,12 +392,27 @@ Die `syncId` kann in der Datenbank gespeichert werden: - ✅ Daten werden korrekt persistiert ### 4. View-Darstellung -**Status: TECHNISCH MÖGLICH** +**Status: ⚠️ NICHT EMPFOHLEN (API-ONLY PATTERN)** -Die Beziehung kann im EspoCRM-Frontend dargestellt werden durch: -- Anzeige in Relationship-Panels -- Konfiguration über Entity Manager → Relationships -- Anpassung der Layouts für die Anzeige von `syncId` als Spalte +**Problem:** Standard EspoCRM Relationship-Panels versuchen inline-editing von Feldern. Bei additionalColumns führt dies zu **405 Method Not Allowed** Fehlern, da die Standard-Panel-UI nicht mit dem Junction-Entity-Pattern kompatibel ist. + +**Versucht & Fehlgeschlagen:** +1. ❌ Direct display of syncId in relationship panel layout → 405 Fehler +2. ❌ Custom View mit actionEditLinkData → Blank views, dann weiter 405 Fehler +3. ❌ Simplified relationship layout ohne syncId → 405 Fehler blieben bestehen + +**ROOT CAUSE:** Standard relationship panels senden HTTP-Requests die nicht mit Junction-Entity-Architektur übereinstimmen. additionalColumns erfordern spezielle Behandlung die nicht durch Standard-UI bereitgestellt wird. + +**LÖSUNG:** API-ONLY Access Pattern +- ✅ Vollständige CRUD via `/api/v1/CAICollectionCDokumente` +- ✅ Kein UI-Panel in CDokumente → keine 405 Fehler +- ✅ Alle Funktionen über REST API verfügbar +- ✅ Perfekt für externe Systeme und Middleware + +**Falls UI Display gewünscht:** +- Option: Custom Panel das direkt die Junction Entity list-view lädt (gefiltert nach documentId) +- Option: Separate Tab/Page für Junction Entity-Management +- Nicht empfohlen: Standard relationship panel mit additionalColumns ## ❌ Was NICHT funktioniert diff --git a/custom/scripts/E2E_TEST_RESULTS.md b/custom/docs/archive/E2E_TEST_RESULTS.md similarity index 100% rename from custom/scripts/E2E_TEST_RESULTS.md rename to custom/docs/archive/E2E_TEST_RESULTS.md diff --git a/custom/scripts/KI_OVERVIEW_SUMMARY.md b/custom/docs/archive/KI_OVERVIEW_SUMMARY.md similarity index 100% rename from custom/scripts/KI_OVERVIEW_SUMMARY.md rename to custom/docs/archive/KI_OVERVIEW_SUMMARY.md diff --git a/custom/scripts/E2E_TESTS_README.md b/custom/docs/tools/E2E_TESTS_README.md similarity index 100% rename from custom/scripts/E2E_TESTS_README.md rename to custom/docs/tools/E2E_TESTS_README.md diff --git a/custom/scripts/KI_OVERVIEW_README.md b/custom/docs/tools/KI_OVERVIEW_README.md similarity index 100% rename from custom/scripts/KI_OVERVIEW_README.md rename to custom/docs/tools/KI_OVERVIEW_README.md diff --git a/custom/scripts/QUICKSTART.md b/custom/docs/tools/QUICKSTART.md similarity index 100% rename from custom/scripts/QUICKSTART.md rename to custom/docs/tools/QUICKSTART.md diff --git a/custom/scripts/VALIDATION_TOOLS.md b/custom/docs/tools/VALIDATION_TOOLS.md similarity index 100% rename from custom/scripts/VALIDATION_TOOLS.md rename to custom/docs/tools/VALIDATION_TOOLS.md diff --git a/custom/scripts/VALIDATOR_README.md b/custom/docs/tools/VALIDATOR_README.md similarity index 100% rename from custom/scripts/VALIDATOR_README.md rename to custom/docs/tools/VALIDATOR_README.md diff --git a/custom/docs/workflows/README.md b/custom/docs/workflows/README.md new file mode 100644 index 00000000..d17860f2 --- /dev/null +++ b/custom/docs/workflows/README.md @@ -0,0 +1,72 @@ +# Workflow Definitions + +This directory contains workflow definitions in JSON format that can be imported into EspoCRM using the workflow manager script. + +## File Format + +### Simple Workflow +```json +{ + "type": "simple", + "name": "workflow-name", + "entity_type": "EntityName", + "trigger_type": "afterRecordSaved", + "is_active": true, + "description": "Description of what this workflow does", + "category": "Category Name", + "conditions_all": [], + "conditions_any": [], + "conditions_formula": null, + "actions": [] +} +``` + +**Trigger Types:** +- `afterRecordSaved` - After record is created or updated +- `afterRecordCreated` - Only after record is created +- `scheduled` - Runs on a schedule +- `manual` - Manually triggered + +**Condition Types:** +- `equals`, `notEquals`, `greaterThan`, `lessThan`, `contains`, `notContains`, `isEmpty`, `isNotEmpty`, `isTrue`, `isFalse`, `wasEqual`, `wasNotEqual`, `changed`, `notChanged` + +**Action Types:** +- `sendEmail` - Send email to recipient +- `createEntity` - Create a new record +- `updateEntity` - Update current record +- `relateTo` - Link to another record +- `unrelateFrom` - Unlink from record +- `applyAssignmentRule` - Apply assignment rules +- `createNotification` - Create notification + +### BPM Flowchart +```json +{ + "type": "bpm", + "name": "flowchart-name", + "target_type": "EntityName", + "is_active": true, + "description": "Description", + "data": { + "list": [] + }, + "elements_data_hash": {}, + "event_start_all_id_list": [] +} +``` + +## Usage + +Import a workflow: +```bash +docker exec espocrm php /var/www/html/custom/scripts/workflow_manager.php import /var/www/html/custom/workflows/your-workflow.json +``` + +Export a workflow: +```bash +docker exec espocrm php /var/www/html/custom/scripts/workflow_manager.php export /var/www/html/custom/workflows/exported.json +``` + +## Examples + +- `vmh-erstberatung-abschliessen.json` - Sends email and sets status when consultation is completed diff --git a/custom/scripts/__pycache__/validate_and_rebuild.cpython-311.pyc b/custom/scripts/__pycache__/validate_and_rebuild.cpython-311.pyc new file mode 100644 index 00000000..4a6496dd Binary files /dev/null and b/custom/scripts/__pycache__/validate_and_rebuild.cpython-311.pyc differ diff --git a/custom/scripts/validate_and_rebuild.py b/custom/scripts/validate_and_rebuild.py index fe794630..6698677e 100644 --- a/custom/scripts/validate_and_rebuild.py +++ b/custom/scripts/validate_and_rebuild.py @@ -739,6 +739,81 @@ class EntityValidator: print_success(f"Alle {len(php_files)} PHP-Dateien sind syntaktisch korrekt") return True + def show_error_logs(self): + """Zeige die letzten Fehlerlog-Einträge aus data/logs/.""" + from datetime import datetime + + print_header("FEHLERLOG ANALYSE") + + logs_path = self.base_path / "data" / "logs" + if not logs_path.exists(): + print_warning("Logs-Verzeichnis nicht gefunden") + return + + # Finde das neueste Log-File + today = datetime.now().strftime("%Y-%m-%d") + log_file = logs_path / f"espo-{today}.log" + + if not log_file.exists(): + # Fallback: Finde das neueste Log-File + log_files = sorted(logs_path.glob("espo-*.log"), key=lambda f: f.stat().st_mtime, reverse=True) + if log_files: + log_file = log_files[0] + print_info(f"Kein Log für heute gefunden, verwende: {log_file.name}") + else: + print_warning("Keine Log-Dateien gefunden") + return + + print_info(f"Analysiere: {log_file.name}") + + try: + with open(log_file, 'r', encoding='utf-8') as f: + lines = f.readlines() + + if not lines: + print_info("Log-Datei ist leer") + return + + # Zeige die letzten 50 Zeilen + last_lines = lines[-50:] + + # Filter für Fehler und Warnungen + errors = [] + warnings = [] + + for line in last_lines: + line_upper = line.upper() + if 'ERROR' in line_upper or 'FATAL' in line_upper or 'EXCEPTION' in line_upper: + errors.append(line.strip()) + elif 'WARNING' in line_upper or 'WARN' in line_upper: + warnings.append(line.strip()) + + if errors: + print_error(f"\n{len(errors)} Fehler in den letzten 50 Log-Zeilen gefunden:\n") + for i, error in enumerate(errors[-10:], 1): # Zeige max. 10 Fehler + print(f"{Colors.RED}{i}.{Colors.END} {error}") + if len(errors) > 10: + print(f"\n{Colors.YELLOW}... und {len(errors) - 10} weitere Fehler{Colors.END}") + + if warnings: + print_warning(f"\n{len(warnings)} Warnungen in den letzten 50 Log-Zeilen gefunden:\n") + for i, warning in enumerate(warnings[-5:], 1): # Zeige max. 5 Warnungen + print(f"{Colors.YELLOW}{i}.{Colors.END} {warning}") + if len(warnings) > 5: + print(f"\n{Colors.YELLOW}... und {len(warnings) - 5} weitere Warnungen{Colors.END}") + + if not errors and not warnings: + print_info("Keine Fehler oder Warnungen in den letzten 50 Log-Zeilen gefunden") + print_info("\nLetzte 10 Log-Zeilen:") + for line in last_lines[-10:]: + print(f" {line.strip()}") + + print(f"\n{Colors.BLUE}ℹ{Colors.END} Vollständige Log-Datei: {log_file}") + print(f"{Colors.BLUE}ℹ{Colors.END} Zum Anzeigen: tail -50 {log_file}") + + except Exception as e: + print_error(f"Fehler beim Lesen der Log-Datei: {e}") + def run_rebuild(self) -> bool: """Führe den EspoCRM Rebuild aus.""" print_header("10. ESPOCRM REBUILD") @@ -811,6 +886,9 @@ class EntityValidator: print_error("Rebuild fehlgeschlagen:") if result.stderr: print(f"\n{result.stderr}") + + # Zeige automatisch die letzten Fehlerlog-Einträge an + self.show_error_logs() return False else: print_warning("Kein EspoCRM Docker-Container gefunden") @@ -862,6 +940,9 @@ class EntityValidator: print_error("Rebuild fehlgeschlagen:") if result.stderr: print(f"\n{result.stderr}") + + # Zeige automatisch die letzten Fehlerlog-Einträge an + self.show_error_logs() return False except subprocess.TimeoutExpired: print_error("Rebuild-Timeout (>60 Sekunden)") diff --git a/custom/workflows/README.md b/custom/workflows/README.md index d17860f2..ffaf5c29 100644 --- a/custom/workflows/README.md +++ b/custom/workflows/README.md @@ -1,72 +1,39 @@ -# Workflow Definitions +# Workflow Documentation -This directory contains workflow definitions in JSON format that can be imported into EspoCRM using the workflow manager script. +Dokumentation für EspoCRM Workflow-Management. -## File Format +## Workflow-Format & Management -### Simple Workflow -```json -{ - "type": "simple", - "name": "workflow-name", - "entity_type": "EntityName", - "trigger_type": "afterRecordSaved", - "is_active": true, - "description": "Description of what this workflow does", - "category": "Category Name", - "conditions_all": [], - "conditions_any": [], - "conditions_formula": null, - "actions": [] -} -``` +Siehe: `custom/docs/workflows/README.md` für vollständige Workflow-Dokumentation inkl.: +- Simple Workflow JSON-Format +- BPM Flowchart Format +- Trigger Types (afterRecordSaved, afterRecordCreated, scheduled, manual) +- Action Types (sendEmail, createEntity, updateEntity, etc.) +- Condition Types +- Import/Export mit workflow_manager.php -**Trigger Types:** -- `afterRecordSaved` - After record is created or updated -- `afterRecordCreated` - Only after record is created -- `scheduled` - Runs on a schedule -- `manual` - Manually triggered +## Workflow-Befehle -**Condition Types:** -- `equals`, `notEquals`, `greaterThan`, `lessThan`, `contains`, `notContains`, `isEmpty`, `isNotEmpty`, `isTrue`, `isFalse`, `wasEqual`, `wasNotEqual`, `changed`, `notChanged` - -**Action Types:** -- `sendEmail` - Send email to recipient -- `createEntity` - Create a new record -- `updateEntity` - Update current record -- `relateTo` - Link to another record -- `unrelateFrom` - Unlink from record -- `applyAssignmentRule` - Apply assignment rules -- `createNotification` - Create notification - -### BPM Flowchart -```json -{ - "type": "bpm", - "name": "flowchart-name", - "target_type": "EntityName", - "is_active": true, - "description": "Description", - "data": { - "list": [] - }, - "elements_data_hash": {}, - "event_start_all_id_list": [] -} -``` - -## Usage - -Import a workflow: ```bash -docker exec espocrm php /var/www/html/custom/scripts/workflow_manager.php import /var/www/html/custom/workflows/your-workflow.json +# Alle Workflows auflisten +php custom/scripts/workflow_manager.php list + +# Workflow importieren +php custom/scripts/workflow_manager.php import custom/workflows/my-workflow.json + +# Alle Workflows exportieren +php custom/scripts/workflow_manager.php export + +# Workflow löschen +php custom/scripts/workflow_manager.php delete workflow-name ``` -Export a workflow: -```bash -docker exec espocrm php /var/www/html/custom/scripts/workflow_manager.php export /var/www/html/custom/workflows/exported.json -``` +## Workflow-Dateien -## Examples +Workflow-Definitionen werden als JSON-Dateien in diesem Verzeichnis gespeichert und können mit dem workflow_manager.php Tool importiert werden. -- `vmh-erstberatung-abschliessen.json` - Sends email and sets status when consultation is completed +**Datei-Naming:** `{workflow-name}.json` (Kleinbuchstaben, Bindestriche) + +--- + +Für Details siehe: **custom/docs/workflows/README.md**