Files
motia/bitbylaw/scripts/test_adressen_sync.py
bitbylaw c770f2c8ee feat: Implement address synchronization between EspoCRM and Advoware
- Add AdressenMapper for transforming addresses between EspoCRM and Advoware formats.
- Create AdressenSync class to handle address creation, update, and deletion synchronization.
- Introduce NotificationManager for managing manual intervention notifications in case of sync issues.
- Implement detailed logging for address sync operations and error handling.
- Ensure READ-ONLY field changes are detected and notified for manual resolution.
2026-02-08 14:29:29 +00:00

235 lines
6.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Test: Adressen-Sync zwischen EspoCRM und Advoware
==================================================
Testet die AdressenSync-Implementierung:
1. CREATE: Neue Adresse von EspoCRM → Advoware
2. UPDATE: Änderung nur R/W Felder
3. READ-ONLY Detection: Notification bei READ-ONLY Änderungen
4. SYNC: Advoware → EspoCRM
"""
import asyncio
import sys
import os
from datetime import datetime
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from services.adressen_sync import AdressenSync
from services.espocrm import EspoCRMAPI
BOLD = '\033[1m'
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RESET = '\033[0m'
def print_success(text):
print(f"{GREEN}{text}{RESET}")
def print_error(text):
print(f"{RED}{text}{RESET}")
def print_info(text):
print(f"{BLUE} {text}{RESET}")
def print_section(title):
print(f"\n{BOLD}{'='*70}{RESET}")
print(f"{BOLD}{title}{RESET}")
print(f"{BOLD}{'='*70}{RESET}\n")
class SimpleLogger:
def debug(self, msg): pass
def info(self, msg): pass
def warning(self, msg): pass
def error(self, msg): pass
class SimpleContext:
def __init__(self):
self.logger = SimpleLogger()
async def main():
print_section("TEST: Adressen-Sync")
context = SimpleContext()
sync = AdressenSync(context=context)
espo = EspoCRMAPI(context=context)
# Test-Daten
TEST_BETNR = 104860
TEST_BETEILIGTE_ID = None # Wird ermittelt
# 1. Finde Beteiligten in EspoCRM
print_section("1. Setup: Finde Test-Beteiligten")
print_info("Suche Beteiligten mit BetNr 104860...")
import json
beteiligte_result = await espo.list_entities(
'CBeteiligte',
where=json.dumps([{
'type': 'equals',
'attribute': 'betNr',
'value': str(TEST_BETNR)
}])
)
if not beteiligte_result.get('list'):
print_error("Beteiligter nicht gefunden!")
return
TEST_BETEILIGTE_ID = beteiligte_result['list'][0]['id']
print_success(f"Beteiligter gefunden: {TEST_BETEILIGTE_ID}")
# 2. Test CREATE
print_section("2. Test CREATE: EspoCRM → Advoware")
# Erstelle Test-Adresse in EspoCRM
print_info("Erstelle Test-Adresse in EspoCRM...")
test_addr_data = {
'name': f'SYNC-TEST Adresse {datetime.now().strftime("%H:%M:%S")}',
'adresseStreet': 'SYNC-TEST Straße 123',
'adressePostalCode': '10115',
'adresseCity': 'Berlin',
'adresseCountry': 'DE',
'isPrimary': False,
'isActive': True,
'beteiligteId': TEST_BETEILIGTE_ID,
'description': f'SYNC-TEST: {datetime.now()}'
}
espo_addr = await espo.create_entity('CAdressen', test_addr_data)
if not espo_addr:
print_error("Konnte EspoCRM Adresse nicht erstellen!")
return
print_success(f"EspoCRM Adresse erstellt: {espo_addr['id']}")
# Sync zu Advoware
print_info("\nSync zu Advoware...")
advo_result = await sync.create_address(espo_addr, TEST_BETNR)
if advo_result:
print_success(
f"✓ Adresse in Advoware erstellt: "
f"Index {advo_result.get('reihenfolgeIndex')}"
)
print(f" Strasse: {advo_result.get('strasse')}")
print(f" PLZ: {advo_result.get('plz')}")
print(f" Ort: {advo_result.get('ort')}")
print(f" bemerkung: {advo_result.get('bemerkung')}")
else:
print_error("✗ CREATE fehlgeschlagen!")
return
# 3. Test UPDATE (nur R/W Felder)
print_section("3. Test UPDATE: Nur R/W Felder")
# Ändere Straße
print_info("Ändere Straße in EspoCRM...")
espo_addr['adresseStreet'] = 'SYNC-TEST Neue Straße 456'
espo_addr['adresseCity'] = 'Hamburg'
await espo.update_entity('CAdressen', espo_addr['id'], {
'adresseStreet': espo_addr['adresseStreet'],
'adresseCity': espo_addr['adresseCity']
})
print_success("EspoCRM aktualisiert")
# Sync zu Advoware
print_info("\nSync UPDATE zu Advoware...")
update_result = await sync.update_address(espo_addr, TEST_BETNR)
if update_result:
print_success("✓ Adresse in Advoware aktualisiert")
print(f" Strasse: {update_result.get('strasse')}")
print(f" Ort: {update_result.get('ort')}")
else:
print_error("✗ UPDATE fehlgeschlagen!")
# 4. Test READ-ONLY Detection
print_section("4. Test READ-ONLY Feld-Änderung")
print_info("Ändere READ-ONLY Feld (isPrimary) in EspoCRM...")
espo_addr['isPrimary'] = True
await espo.update_entity('CAdressen', espo_addr['id'], {
'isPrimary': True
})
print_success("EspoCRM aktualisiert (isPrimary = true)")
# Sync zu Advoware (sollte Notification erstellen)
print_info("\nSync zu Advoware (sollte Notification erstellen)...")
update_result2 = await sync.update_address(espo_addr, TEST_BETNR)
if update_result2:
print_success("✓ UPDATE erfolgreich")
print_info(" → Notification sollte erstellt worden sein!")
print_info(" → Prüfe EspoCRM Tasks/Notifications")
else:
print_error("✗ UPDATE fehlgeschlagen!")
# 5. Test SYNC from Advoware
print_section("5. Test SYNC: Advoware → EspoCRM")
print_info("Synct alle Adressen von Advoware...")
stats = await sync.sync_from_advoware(TEST_BETNR, TEST_BETEILIGTE_ID)
print_success(f"✓ Sync abgeschlossen:")
print(f" Created: {stats['created']}")
print(f" Updated: {stats['updated']}")
print(f" Errors: {stats['errors']}")
# 6. Cleanup
print_section("6. Cleanup")
print_info("Lösche Test-Adresse aus EspoCRM...")
# In EspoCRM löschen
await espo.delete_entity('CAdressen', espo_addr['id'])
print_success("EspoCRM Adresse gelöscht")
# DELETE Handler testen
print_info("\nTestweise DELETE-Handler aufrufen...")
delete_result = await sync.handle_address_deletion(espo_addr, TEST_BETNR)
if delete_result:
print_success("✓ DELETE Notification erstellt")
print_info(" → Prüfe EspoCRM Tasks für manuelle Löschung")
else:
print_error("✗ DELETE Notification fehlgeschlagen!")
print_section("ZUSAMMENFASSUNG")
print_success("✓ CREATE: Funktioniert")
print_success("✓ UPDATE (R/W): Funktioniert")
print_success("✓ READ-ONLY Detection: Funktioniert")
print_success("✓ SYNC from Advoware: Funktioniert")
print_success("✓ DELETE Notification: Funktioniert")
print_info("\n⚠ WICHTIG:")
print(" - Test-Adresse in Advoware manuell löschen!")
print(f" - BetNr: {TEST_BETNR}")
print(" - Suche nach: SYNC-TEST")
if __name__ == '__main__':
asyncio.run(main())