diff --git a/src/steps/crm/akte/akte_sync_event_step.py b/src/steps/crm/akte/akte_sync_event_step.py index 01086d0..c618cdc 100644 --- a/src/steps/crm/akte/akte_sync_event_step.py +++ b/src/steps/crm/akte/akte_sync_event_step.py @@ -399,12 +399,42 @@ async def _run_xai_sync( ctx.logger.info("─" * 60) try: - # ── Ensure collection exists ─────────────────────────────────── - collection_id = await upload_utils.ensure_collection(akte, xai, espocrm) + # ── Collection-ID ermitteln ──────────────────────────────────── + ai_aktivierungsstatus = str(akte.get('aiAktivierungsstatus') or '').lower() + collection_id = akte.get('aiCollectionId') + if not collection_id: - ctx.logger.error("❌ Could not obtain xAI collection – aborting xAI sync") - await espocrm.update_entity('CAkten', akte_id, {'aiSyncStatus': 'failed'}) - return + if ai_aktivierungsstatus == 'new': + # Status 'new' → neue Collection anlegen + ctx.logger.info(" Status 'new' → Erstelle neue xAI Collection...") + collection_id = await upload_utils.ensure_collection(akte, xai, espocrm) + if not collection_id: + ctx.logger.error("❌ xAI Collection konnte nicht erstellt werden – Sync abgebrochen") + await espocrm.update_entity('CAkten', akte_id, {'aiSyncStatus': 'failed'}) + return + ctx.logger.info(f" ✅ Collection erstellt: {collection_id}") + # aiAktivierungsstatus → 'aktiv' wird in handler final_update gesetzt + else: + # aktiv (oder anderer Status) aber keine Collection-ID → Konfigurationsfehler + ctx.logger.error( + f"❌ aiAktivierungsstatus='{ai_aktivierungsstatus}' aber keine aiCollectionId vorhanden – " + f"xAI Sync abgebrochen. Bitte Collection-ID in EspoCRM eintragen." + ) + await espocrm.update_entity('CAkten', akte_id, {'aiSyncStatus': 'failed'}) + return + else: + # Collection-ID vorhanden → verifizieren ob sie noch in xAI existiert + try: + col = await xai.get_collection(collection_id) + if not col: + ctx.logger.error(f"❌ Collection {collection_id} existiert nicht mehr in xAI – Sync abgebrochen") + await espocrm.update_entity('CAkten', akte_id, {'aiSyncStatus': 'failed'}) + return + ctx.logger.info(f" ✅ Collection verifiziert: {collection_id}") + except Exception as e: + ctx.logger.error(f"❌ Collection-Verifizierung fehlgeschlagen: {e} – Sync abgebrochen") + await espocrm.update_entity('CAkten', akte_id, {'aiSyncStatus': 'failed'}) + return ctx.logger.info(f" Documents to check: {len(docs)}")