92 lines
3.2 KiB
Python
92 lines
3.2 KiB
Python
"""VMH Webhook - Document Create"""
|
|
import json
|
|
import datetime
|
|
from typing import Any
|
|
from motia import FlowContext, http, ApiRequest, ApiResponse
|
|
|
|
|
|
config = {
|
|
"name": "VMH Webhook Document Create",
|
|
"description": "Empfängt Create-Webhooks von EspoCRM für Documents",
|
|
"flows": ["vmh-documents"],
|
|
"triggers": [
|
|
http("POST", "/vmh/webhook/document/create")
|
|
],
|
|
"enqueues": ["vmh.document.create"],
|
|
}
|
|
|
|
|
|
async def handler(request: ApiRequest, ctx: FlowContext[Any]) -> ApiResponse:
|
|
"""
|
|
Webhook handler for Document creation in EspoCRM.
|
|
|
|
Receives batch or single entity notifications and emits queue events
|
|
for each entity ID to be synced to xAI.
|
|
"""
|
|
try:
|
|
payload = request.body or []
|
|
|
|
ctx.logger.info("=" * 80)
|
|
ctx.logger.info("📥 VMH WEBHOOK: DOCUMENT CREATE")
|
|
ctx.logger.info("=" * 80)
|
|
ctx.logger.debug(f"Payload: {json.dumps(payload, indent=2, ensure_ascii=False)}")
|
|
|
|
# Collect all IDs from batch
|
|
entity_ids = set()
|
|
entity_type = 'CDokumente' # Default
|
|
|
|
if isinstance(payload, list):
|
|
for entity in payload:
|
|
if isinstance(entity, dict) and 'id' in entity:
|
|
entity_ids.add(entity['id'])
|
|
# Take entityType from first entity if present
|
|
if entity_type == 'CDokumente':
|
|
entity_type = entity.get('entityType', 'CDokumente')
|
|
elif isinstance(payload, dict) and 'id' in payload:
|
|
entity_ids.add(payload['id'])
|
|
entity_type = payload.get('entityType', 'CDokumente')
|
|
|
|
ctx.logger.info(f"{len(entity_ids)} document IDs found for create sync")
|
|
|
|
# Emit events for queue processing (deduplication via lock in event handler)
|
|
for entity_id in entity_ids:
|
|
await ctx.enqueue({
|
|
'topic': 'vmh.document.create',
|
|
'data': {
|
|
'entity_id': entity_id,
|
|
'entity_type': entity_type,
|
|
'action': 'create',
|
|
'timestamp': payload[0].get('modifiedAt') if isinstance(payload, list) and payload else None
|
|
}
|
|
})
|
|
|
|
ctx.logger.info("✅ Document Create Webhook processed: "
|
|
f"{len(entity_ids)} events emitted")
|
|
|
|
return ApiResponse(
|
|
status=200,
|
|
body={
|
|
'success': True,
|
|
'message': f'{len(entity_ids)} document(s) enqueued for sync',
|
|
'entity_ids': list(entity_ids)
|
|
}
|
|
)
|
|
|
|
except Exception as e:
|
|
ctx.logger.error("=" * 80)
|
|
ctx.logger.error("❌ ERROR: DOCUMENT CREATE WEBHOOK")
|
|
ctx.logger.error("=" * 80)
|
|
ctx.logger.error(f"Error: {e}")
|
|
ctx.logger.error(f"Entity IDs attempted: {list(entity_ids) if 'entity_ids' in locals() else 'N/A'}")
|
|
ctx.logger.error(f"Full Payload: {json.dumps(request.body, indent=2, ensure_ascii=False)}")
|
|
ctx.logger.error(f"Timestamp: {datetime.datetime.now().isoformat()}")
|
|
ctx.logger.error("=" * 80)
|
|
|
|
return ApiResponse(
|
|
status=500,
|
|
body={
|
|
'success': False,
|
|
'error': str(e)
|
|
}
|
|
)
|