Sync all employees in loop, remove employee_kuerzel requirement, update README
This commit is contained in:
@@ -168,7 +168,7 @@ Beide Systeme werden auf gemeinsames Format normalisiert (Berlin TZ):
|
|||||||
{
|
{
|
||||||
"data": {
|
"data": {
|
||||||
"body": {
|
"body": {
|
||||||
"employee_kuerzel": "SB" // Erforderlich, kein Default
|
// Kein employee_kuerzel erforderlich, syncronisiert alle Mitarbeiter automatisch
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -383,19 +383,40 @@ async def safe_update_advoware_appointment(advoware, frnr, data, write_allowed,
|
|||||||
return
|
return
|
||||||
await update_advoware_appointment(advoware, frnr, data, employee_kuerzel)
|
await update_advoware_appointment(advoware, frnr, data, employee_kuerzel)
|
||||||
|
|
||||||
async def safe_delete_advoware_appointment(advoware, frnr, write_allowed):
|
async def get_advoware_employees(advoware):
|
||||||
"""Safe wrapper for deleting Advoware appointments with write permission check."""
|
"""Fetch list of employees from Advoware."""
|
||||||
if not write_allowed:
|
try:
|
||||||
logger.warning("Cannot delete in Advoware, write not allowed")
|
result = await advoware.api_call('api/v1/advonet/Anwaelte', method='GET')
|
||||||
return
|
employees = result if isinstance(result, list) else []
|
||||||
await delete_advoware_appointment(advoware, frnr)
|
logger.info(f"Fetched {len(employees)} Advoware employees")
|
||||||
|
return employees
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Failed to fetch Advoware employees: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
async def handler(event, context):
|
async def handler(event, context):
|
||||||
"""Main event handler for calendar sync."""
|
"""Main event handler for calendar sync."""
|
||||||
employee_kuerzel = event.get('data', {}).get('body', {}).get('employee_kuerzel')
|
logger.info("Starting calendar sync for all employees")
|
||||||
if not employee_kuerzel:
|
|
||||||
raise ValueError("employee_kuerzel is required in the event data")
|
try:
|
||||||
logger.info(f"Starting calendar sync for {employee_kuerzel}")
|
logger.debug("Initializing Advoware API")
|
||||||
|
advoware = AdvowareAPI(context)
|
||||||
|
|
||||||
|
# Alle Mitarbeiter abrufen
|
||||||
|
logger.info("Rufe Advoware Mitarbeiter ab...")
|
||||||
|
employees = await get_advoware_employees(advoware)
|
||||||
|
if not employees:
|
||||||
|
logger.error("Keine Mitarbeiter gefunden. Sync abgebrochen.")
|
||||||
|
return {'status': 500, 'body': {'error': 'Keine Mitarbeiter gefunden'}}
|
||||||
|
|
||||||
|
total_synced = 0
|
||||||
|
for employee in employees:
|
||||||
|
kuerzel = employee.get('kuerzel') or employee.get('anwalt')
|
||||||
|
if not kuerzel:
|
||||||
|
logger.warning(f"Mitarbeiter ohne Kürzel übersprungen: {employee}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
logger.info(f"Starting calendar sync for {kuerzel}")
|
||||||
|
|
||||||
redis_client = redis.Redis(
|
redis_client = redis.Redis(
|
||||||
host=Config.REDIS_HOST,
|
host=Config.REDIS_HOST,
|
||||||
@@ -404,19 +425,19 @@ async def handler(event, context):
|
|||||||
socket_timeout=Config.REDIS_TIMEOUT_SECONDS
|
socket_timeout=Config.REDIS_TIMEOUT_SECONDS
|
||||||
)
|
)
|
||||||
|
|
||||||
|
CALENDAR_SYNC_LOCK_KEY = f'calendar_sync_lock_{kuerzel}'
|
||||||
|
|
||||||
try:
|
try:
|
||||||
logger.debug("Initializing Google service")
|
logger.debug("Initializing Google service")
|
||||||
service = await get_google_service()
|
service = await get_google_service()
|
||||||
logger.debug(f"Ensuring Google calendar for {employee_kuerzel}")
|
logger.debug(f"Ensuring Google calendar for {kuerzel}")
|
||||||
calendar_id = await ensure_google_calendar(service, employee_kuerzel)
|
calendar_id = await ensure_google_calendar(service, kuerzel)
|
||||||
logger.debug("Initializing Advoware API")
|
|
||||||
advoware = AdvowareAPI(context)
|
|
||||||
|
|
||||||
conn = await connect_db()
|
conn = await connect_db()
|
||||||
try:
|
try:
|
||||||
# Fetch fresh data
|
# Fetch fresh data
|
||||||
logger.info("Fetching fresh data from APIs")
|
logger.info("Fetching fresh data from APIs")
|
||||||
adv_appointments = await fetch_advoware_appointments(advoware, employee_kuerzel)
|
adv_appointments = await fetch_advoware_appointments(advoware, kuerzel)
|
||||||
adv_map = {str(app['frNr']): app for app in adv_appointments if app.get('frNr')}
|
adv_map = {str(app['frNr']): app for app in adv_appointments if app.get('frNr')}
|
||||||
google_events = await fetch_google_events(service, calendar_id)
|
google_events = await fetch_google_events(service, calendar_id)
|
||||||
google_map = {evt['id']: evt for evt in google_events}
|
google_map = {evt['id']: evt for evt in google_events}
|
||||||
@@ -427,7 +448,7 @@ async def handler(event, context):
|
|||||||
SELECT * FROM calendar_sync
|
SELECT * FROM calendar_sync
|
||||||
WHERE employee_kuerzel = $1 AND deleted = FALSE
|
WHERE employee_kuerzel = $1 AND deleted = FALSE
|
||||||
""",
|
""",
|
||||||
employee_kuerzel
|
kuerzel
|
||||||
)
|
)
|
||||||
logger.info(f"Fetched {len(rows)} existing sync rows")
|
logger.info(f"Fetched {len(rows)} existing sync rows")
|
||||||
|
|
||||||
@@ -447,7 +468,7 @@ async def handler(event, context):
|
|||||||
INSERT INTO calendar_sync (employee_kuerzel, advoware_frnr, google_event_id, source_system, sync_strategy, sync_status, advoware_write_allowed)
|
INSERT INTO calendar_sync (employee_kuerzel, advoware_frnr, google_event_id, source_system, sync_strategy, sync_status, advoware_write_allowed)
|
||||||
VALUES ($1, $2, $3, 'advoware', 'source_system_wins', 'synced', FALSE);
|
VALUES ($1, $2, $3, 'advoware', 'source_system_wins', 'synced', FALSE);
|
||||||
""",
|
""",
|
||||||
employee_kuerzel, int(frnr), event_id
|
kuerzel, int(frnr), event_id
|
||||||
)
|
)
|
||||||
logger.info(f"Phase 1: Created new from Advoware: frNr {frnr}, event_id {event_id}")
|
logger.info(f"Phase 1: Created new from Advoware: frNr {frnr}, event_id {event_id}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -458,7 +479,7 @@ async def handler(event, context):
|
|||||||
for event_id, evt in google_map.items():
|
for event_id, evt in google_map.items():
|
||||||
if event_id not in db_google_index:
|
if event_id not in db_google_index:
|
||||||
try:
|
try:
|
||||||
frnr = await safe_create_advoware_appointment(advoware, standardize_appointment_data(evt, 'google'), employee_kuerzel, True)
|
frnr = await safe_create_advoware_appointment(advoware, standardize_appointment_data(evt, 'google'), kuerzel, True)
|
||||||
if frnr and str(frnr) != 'None':
|
if frnr and str(frnr) != 'None':
|
||||||
async with conn.transaction():
|
async with conn.transaction():
|
||||||
await conn.execute(
|
await conn.execute(
|
||||||
@@ -466,7 +487,7 @@ async def handler(event, context):
|
|||||||
INSERT INTO calendar_sync (employee_kuerzel, advoware_frnr, google_event_id, source_system, sync_strategy, sync_status, advoware_write_allowed)
|
INSERT INTO calendar_sync (employee_kuerzel, advoware_frnr, google_event_id, source_system, sync_strategy, sync_status, advoware_write_allowed)
|
||||||
VALUES ($1, $2, $3, 'google', 'source_system_wins', 'synced', TRUE);
|
VALUES ($1, $2, $3, 'google', 'source_system_wins', 'synced', TRUE);
|
||||||
""",
|
""",
|
||||||
employee_kuerzel, int(frnr), event_id
|
kuerzel, int(frnr), event_id
|
||||||
)
|
)
|
||||||
logger.info(f"Phase 2: Created new from Google: event_id {event_id}, frNr {frnr}")
|
logger.info(f"Phase 2: Created new from Google: event_id {event_id}, frNr {frnr}")
|
||||||
else:
|
else:
|
||||||
@@ -505,7 +526,7 @@ async def handler(event, context):
|
|||||||
elif row['source_system'] == 'google' and row['advoware_write_allowed']:
|
elif row['source_system'] == 'google' and row['advoware_write_allowed']:
|
||||||
# Recreate in Advoware
|
# Recreate in Advoware
|
||||||
try:
|
try:
|
||||||
new_frnr = await safe_create_advoware_appointment(advoware, standardize_appointment_data(google_map[event_id], 'google'), employee_kuerzel, row['advoware_write_allowed'])
|
new_frnr = await safe_create_advoware_appointment(advoware, standardize_appointment_data(google_map[event_id], 'google'), kuerzel, row['advoware_write_allowed'])
|
||||||
if new_frnr and str(new_frnr) != 'None':
|
if new_frnr and str(new_frnr) != 'None':
|
||||||
async with conn.transaction():
|
async with conn.transaction():
|
||||||
await conn.execute("UPDATE calendar_sync SET advoware_frnr = $1, sync_status = 'synced', last_sync = $3 WHERE sync_id = $2;", int(new_frnr), row['sync_id'], datetime.datetime.now(BERLIN_TZ))
|
await conn.execute("UPDATE calendar_sync SET advoware_frnr = $1, sync_status = 'synced', last_sync = $3 WHERE sync_id = $2;", int(new_frnr), row['sync_id'], datetime.datetime.now(BERLIN_TZ))
|
||||||
@@ -654,12 +675,18 @@ async def handler(event, context):
|
|||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
||||||
redis_client.delete(CALENDAR_SYNC_LOCK_KEY)
|
redis_client.delete(CALENDAR_SYNC_LOCK_KEY)
|
||||||
logger.info(f"Calendar sync completed for {employee_kuerzel}")
|
logger.info(f"Calendar sync completed for {kuerzel}")
|
||||||
return {'status': 200, 'body': {'status': 'completed'}}
|
total_synced += 1
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Sync failed for {employee_kuerzel}: {e}")
|
logger.error(f"Sync failed for {kuerzel}: {e}")
|
||||||
redis_client.delete(CALENDAR_SYNC_LOCK_KEY)
|
redis_client.delete(CALENDAR_SYNC_LOCK_KEY)
|
||||||
|
|
||||||
|
logger.info(f"Calendar sync completed for all employees. Total synced: {total_synced}")
|
||||||
|
return {'status': 200, 'body': {'status': 'completed', 'total_synced': total_synced}}
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"Sync failed: {e}")
|
||||||
return {'status': 500, 'body': {'error': str(e)}}
|
return {'status': 500, 'body': {'error': str(e)}}
|
||||||
|
|
||||||
# Motia Step Configuration
|
# Motia Step Configuration
|
||||||
|
|||||||
Reference in New Issue
Block a user