fix: Event-bus workflow trigger, RBAC on all routes, search provider, events, cron jobs

Critical fixes:
- Event Bus → Workflow auto-trigger: wildcard subscription starts workflows on matching events
- Kommunikation routes: require_permission on all 30+ endpoints (comm:read/write/delete/manage)
- Permissions routes: require_permission('permissions:admin') on all management endpoints
- CompanySearchProvider registered in auto_register_providers()

Medium fixes:
- system_notif events: 10 event_bus.publish() calls added (lead.created, contact.created/updated,
  task.created/overdue, mail.received, user.created, workflow.completed, notification.created, backup.*)
- Cron jobs: backup_check (daily), search_index_check (daily), workflow_timeout (5min) registered
- AI tool permission: call_crm_api now requires 'ai:write' permission
- New file: automation/jobs.py with backup_check and search_index_check functions
This commit is contained in:
Agent Zero
2026-07-25 03:22:55 +02:00
parent b01c798739
commit 6e7e39d101
14 changed files with 266 additions and 22 deletions
+108
View File
@@ -0,0 +1,108 @@
"""ARQ background jobs for the Automation plugin."""
from __future__ import annotations
import logging
from typing import Any
from app.core.db import get_session_factory
logger = logging.getLogger(__name__)
async def backup_check(ctx: dict[str, Any]) -> None:
"""Check if backups are current and publish backup events.
Runs daily at 2:00. Checks the last backup timestamp from system settings
and publishes backup.completed or backup.failed events accordingly.
"""
from app.core.event_bus import get_event_bus
from sqlalchemy import text
event_bus = get_event_bus()
factory = get_session_factory()
async with factory() as db:
try:
# Check last backup timestamp from system settings
result = await db.execute(
text("SELECT value FROM system_settings WHERE key = 'last_backup_at' LIMIT 1")
)
row = result.mappings().first()
if row and row["value"]:
logger.info("Backup check: last backup at %s", row["value"])
# Publish backup.completed event
await event_bus.publish('backup.completed', {
'tenant_id': None,
'user_id': None,
'timestamp': row["value"],
'title': 'Backup erfolgreich',
'body': f'Letztes Backup: {row["value"]}',
})
else:
logger.warning("Backup check: no backup timestamp found")
await event_bus.publish('backup.failed', {
'tenant_id': None,
'user_id': None,
'title': 'Backup fehlgeschlagen',
'body': 'Kein Backup-Zeitstempel gefunden',
})
except Exception:
logger.exception("Backup check failed")
await event_bus.publish('backup.failed', {
'tenant_id': None,
'user_id': None,
'title': 'Backup fehlgeschlagen',
'body': 'Backup-Check fehlgeschlagen',
})
logger.info("Backup check complete")
async def search_index_check(ctx: dict[str, Any]) -> None:
"""Check if search index is current and log status.
Runs daily at 3:00. Checks for entities without embeddings
and logs the count. Publishes status via logging only.
"""
from sqlalchemy import text
factory = get_session_factory()
async with factory() as db:
try:
# Check for contacts without embeddings
result = await db.execute(
text("SELECT COUNT(*) as cnt FROM contacts WHERE deleted_at IS NULL AND embedding IS NULL")
)
row = result.mappings().first()
contacts_missing = row["cnt"] if row else 0
# Check for mails without embeddings
result = await db.execute(
text("SELECT COUNT(*) as cnt FROM mails WHERE embedding IS NULL")
)
row = result.mappings().first()
mails_missing = row["cnt"] if row else 0
# Check for files without embeddings
result = await db.execute(
text("SELECT COUNT(*) as cnt FROM files WHERE deleted_at IS NULL AND embedding IS NULL")
)
row = result.mappings().first()
files_missing = row["cnt"] if row else 0
total_missing = contacts_missing + mails_missing + files_missing
if total_missing > 0:
logger.warning(
"Search index check: %d entities missing embeddings (contacts=%d, mails=%d, files=%d)",
total_missing, contacts_missing, mails_missing, files_missing,
)
else:
logger.info("Search index check: all entities have embeddings")
except Exception:
logger.exception("Search index check failed")
logger.info("Search index check complete")
+30
View File
@@ -15,6 +15,7 @@ from typing import Any
from app.plugins.base import BasePlugin
from app.plugins.manifest import (
CronJobContribution,
FrontendMenuItem,
FrontendPageRoute,
FrontendSettingsPage,
@@ -92,6 +93,29 @@ class AutomationPlugin(BasePlugin):
order=60,
),
],
cron_jobs=[
CronJobContribution(
name="backup_check",
cron_expression="0 2 * * *",
job_type="custom",
target_name="backup_check",
plugin_name="automation",
),
CronJobContribution(
name="search_index_check",
cron_expression="0 3 * * *",
job_type="custom",
target_name="search_index_check",
plugin_name="automation",
),
CronJobContribution(
name="check_workflow_timeouts",
cron_expression="*/5 * * * *",
job_type="custom",
target_name="check_workflow_timeouts",
plugin_name="automation",
),
],
)
def __init__(self) -> None:
@@ -127,6 +151,12 @@ class AutomationPlugin(BasePlugin):
logger.info("Registered MiniApp '%s' from manifest", miniapp.app_id)
except Exception:
logger.exception("Failed to register MiniApps from manifest")
# Register own cron jobs from manifest
try:
await self.register_plugin_contributions(db, self.manifest.name, self.manifest)
logger.info("Registered own cron jobs from manifest")
except Exception:
logger.exception("Failed to register own cron jobs")
logger.info("Automation plugin activated")
async def on_deactivate(self, db, service_container, event_bus) -> None: