diff --git a/bitbylaw/steps/advoware_cal_sync/calendar_sync_event_step.py b/bitbylaw/steps/advoware_cal_sync/calendar_sync_event_step.py index b67a93ae..c7301362 100644 --- a/bitbylaw/steps/advoware_cal_sync/calendar_sync_event_step.py +++ b/bitbylaw/steps/advoware_cal_sync/calendar_sync_event_step.py @@ -88,26 +88,48 @@ async def get_google_service(context=None): @backoff.on_exception(backoff.expo, HttpError, max_tries=4, base=3, giveup=lambda e: e.resp.status not in [403, 429, 500, 502, 503, 504]) async def ensure_google_calendar(service, employee_kuerzel, context=None): - """Ensure Google Calendar exists for employee.""" + """Ensure Google Calendar exists for employee and has correct ACL.""" calendar_name = f"AW-{employee_kuerzel}" try: calendar_list = service.calendarList().list().execute() + calendar_id = None for calendar in calendar_list.get('items', []): if calendar['summary'] == calendar_name: - return calendar['id'] - # Create new - calendar_body = { - 'summary': calendar_name, - 'timeZone': 'Europe/Berlin' - } - created = service.calendars().insert(body=calendar_body).execute() - calendar_id = created['id'] - # Share with main account if needed + calendar_id = calendar['id'] + break + + if not calendar_id: + # Create new calendar + calendar_body = { + 'summary': calendar_name, + 'timeZone': 'Europe/Berlin' + } + created = service.calendars().insert(body=calendar_body).execute() + calendar_id = created['id'] + log_operation('info', f"Created new Google calendar {calendar_name} with ID {calendar_id}", context=context) + + # Ensure ACL rule exists acl_rule = { 'scope': {'type': 'user', 'value': 'lehmannundpartner@gmail.com'}, 'role': 'owner' } - service.acl().insert(calendarId=calendar_id, body=acl_rule).execute() + + # Check existing ACL rules + acl_list = service.acl().list(calendarId=calendar_id).execute() + acl_exists = False + for rule in acl_list.get('items', []): + if (rule.get('scope', {}).get('type') == 'user' and + rule.get('scope', {}).get('value') == 'lehmannundpartner@gmail.com' and + rule.get('role') == 'owner'): + acl_exists = True + break + + if not acl_exists: + service.acl().insert(calendarId=calendar_id, body=acl_rule).execute() + log_operation('info', f"Added ACL rule for calendar {calendar_name} (ID: {calendar_id})", context=context) + else: + log_operation('debug', f"ACL rule already exists for calendar {calendar_name} (ID: {calendar_id})", context=context) + return calendar_id except HttpError as e: log_operation('error', f"Google API error for calendar {employee_kuerzel}: {e}", context=context)