88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
"""VMH Webhook - Document Delete"""
|
|
import json
|
|
from typing import Any
|
|
from motia import FlowContext, http, ApiRequest, ApiResponse
|
|
|
|
|
|
config = {
|
|
"name": "VMH Webhook Document Delete",
|
|
"description": "Empfängt Delete-Webhooks von EspoCRM für Documents",
|
|
"flows": ["vmh-documents"],
|
|
"triggers": [
|
|
http("POST", "/vmh/webhook/document/delete")
|
|
],
|
|
"enqueues": ["vmh.document.delete"],
|
|
}
|
|
|
|
|
|
async def handler(request: ApiRequest, ctx: FlowContext[Any]) -> ApiResponse:
|
|
"""
|
|
Webhook handler for Document deletion in EspoCRM.
|
|
|
|
Receives batch or single entity notifications and emits queue events
|
|
for each entity ID to be removed from xAI.
|
|
"""
|
|
try:
|
|
payload = request.body or []
|
|
|
|
ctx.logger.info("=" * 80)
|
|
ctx.logger.info("📥 VMH WEBHOOK: DOCUMENT DELETE")
|
|
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 delete sync")
|
|
|
|
# Emit events for queue processing
|
|
for entity_id in entity_ids:
|
|
await ctx.enqueue({
|
|
'topic': 'vmh.document.delete',
|
|
'data': {
|
|
'entity_id': entity_id,
|
|
'entity_type': entity_type,
|
|
'action': 'delete',
|
|
'timestamp': payload[0].get('deletedAt') if isinstance(payload, list) and payload else None
|
|
}
|
|
})
|
|
|
|
ctx.logger.info("✅ Document Delete Webhook processed: "
|
|
f"{len(entity_ids)} events emitted")
|
|
|
|
return ApiResponse(
|
|
status=200,
|
|
body={
|
|
'success': True,
|
|
'message': f'{len(entity_ids)} document(s) enqueued for deletion',
|
|
'entity_ids': list(entity_ids)
|
|
}
|
|
)
|
|
|
|
except Exception as e:
|
|
ctx.logger.error("=" * 80)
|
|
ctx.logger.error("❌ ERROR: DOCUMENT DELETE WEBHOOK")
|
|
ctx.logger.error(f"Error: {e}")
|
|
ctx.logger.error(f"Payload: {request.body}")
|
|
ctx.logger.error("=" * 80)
|
|
|
|
return ApiResponse(
|
|
status=500,
|
|
body={
|
|
'success': False,
|
|
'error': str(e)
|
|
}
|
|
)
|