diff --git a/src/clear_bookings.py b/src/clear_bookings.py index 7289724..db9a993 100644 --- a/src/clear_bookings.py +++ b/src/clear_bookings.py @@ -375,7 +375,7 @@ def clear(target_calendars: list, is_test: bool=False) -> dict: other_bookings = find_other_bookings(event, calendar) # Find free alternative rooms for the time slot of the declined event - alternatives = find_alternatives(event, principal) + alternatives = find_alternatives(event, principal, target_calendars) # Create a set for all events as an overview event.is_declined = True @@ -622,15 +622,23 @@ def find_other_bookings(event: DavEvent, calendar: caldav.Calendar) -> list[DavE and e.extended_uid != event.extended_uid and not e.missing_required_fields] -def find_alternatives(event: DavEvent, principal: Principal) -> list[Calendar]: +def find_alternatives(event: DavEvent, principal: Principal, + target_calendars: list) -> list[Calendar]: """ Find alternative rooms for the time slot of the declined event. :param event: The event to find alternatives for. :param principal: The principal to search for alternative rooms. + :param target_calendars: Calendars administrated by the current user :return: List of alternative calendars that are available for the time slot. """ # Get all calendars of the principal calendars = principal.calendars() + alternative_calendars = { + calendar.name: [c.name for c in calendar.alternatives.all()] + for calendar in target_calendars + } + print("Alternative calendars for event calendar: " + f"{', '.join([a for a in alternative_calendars[event.obj.parent.id]])}") alternatives = [] for calendar in calendars: @@ -638,6 +646,16 @@ def find_alternatives(event: DavEvent, principal: Principal) -> list[Calendar]: if calendar.id == event.obj.parent.id: continue + # Skip if the calendar is not administrated by the current user + if calendar.id not in alternative_calendars.keys(): + continue + + # Skip if the calendar is not an alternative to the calendar of the + # declined event + if calendar.id not in alternative_calendars[event.obj.parent.id]: + continue + + # Search for events in the alternative calendar that overlap with the # declined event events_fetched = calendar.search( @@ -659,6 +677,8 @@ def find_alternatives(event: DavEvent, principal: Principal) -> list[Calendar]: if not blocked: alternatives.append(calendar) + print("Available alternative calendars for event: " + f"{', '.join([a.id for a in alternatives])}") return alternatives