- Implemented create, update, and delete webhook handlers for Beteiligte. - Implemented create, update, and delete webhook handlers for Document entities. - Added logging and error handling for each webhook handler. - Created a universal step for generating document previews. - Ensured payload validation and entity ID extraction for batch processing.
69 lines
2.5 KiB
Python
69 lines
2.5 KiB
Python
"""
|
|
Akte Sync - EspoCRM Webhook
|
|
|
|
Empfängt EspoCRM-Webhooks für CAkten (create / update / delete).
|
|
Schreibt die Entity-ID in die Redis-Queue `akte:pending_entity_ids`
|
|
mit 10-Sekunden-Debounce — der Cron-Poller übernimmt den Rest.
|
|
|
|
Route: POST /akte/webhook/update
|
|
Payload: { "id": "..." } oder [{ "id": "..." }, ...]
|
|
"""
|
|
|
|
import json
|
|
import time
|
|
from typing import Any
|
|
from motia import FlowContext, http, ApiRequest, ApiResponse
|
|
|
|
|
|
config = {
|
|
"name": "Akte Webhook - EspoCRM",
|
|
"description": "Empfängt EspoCRM-Webhooks für CAkten und queued Entity-IDs für den Sync",
|
|
"flows": ["akte-sync"],
|
|
"triggers": [http("POST", "/crm/akte/webhook/update")],
|
|
"enqueues": [],
|
|
}
|
|
|
|
PENDING_KEY = "akte:pending_entity_ids"
|
|
|
|
|
|
async def handler(request: ApiRequest, ctx: FlowContext[Any]) -> ApiResponse:
|
|
try:
|
|
payload = request.body or {}
|
|
|
|
ctx.logger.info("=" * 60)
|
|
ctx.logger.info("📥 AKTE WEBHOOK")
|
|
ctx.logger.info(f" Payload: {json.dumps(payload, ensure_ascii=False)[:200]}")
|
|
|
|
# ── Collect entity IDs ─────────────────────────────────────
|
|
entity_ids: set[str] = set()
|
|
if isinstance(payload, list):
|
|
for item in payload:
|
|
if isinstance(item, dict) and 'id' in item:
|
|
entity_ids.add(item['id'])
|
|
elif isinstance(payload, dict) and 'id' in payload:
|
|
entity_ids.add(payload['id'])
|
|
|
|
if not entity_ids:
|
|
ctx.logger.warn("⚠️ No entity IDs in payload")
|
|
return ApiResponse(status_code=400, body={"error": "No entity ID found in payload"})
|
|
|
|
# ── Push to Redis with current timestamp (debounce in cron) ─
|
|
from services.redis_client import get_redis_client
|
|
redis_client = get_redis_client(strict=False)
|
|
if not redis_client:
|
|
ctx.logger.error("❌ Redis unavailable")
|
|
return ApiResponse(status_code=503, body={"error": "Service unavailable"})
|
|
|
|
ts = time.time()
|
|
mapping = {eid: ts for eid in entity_ids}
|
|
redis_client.zadd(PENDING_KEY, mapping)
|
|
|
|
ctx.logger.info(f"✅ Queued {len(entity_ids)} entity ID(s): {entity_ids}")
|
|
ctx.logger.info("=" * 60)
|
|
|
|
return ApiResponse(status_code=200, body={"queued": len(entity_ids)})
|
|
|
|
except Exception as e:
|
|
ctx.logger.error(f"❌ Webhook error: {e}")
|
|
return ApiResponse(status_code=500, body={"error": str(e)})
|