"""Schedule logic.""" from typing import Type from marshmallow import ValidationError from owsresponse import response from abacus_schedule.constants import constants, error as err_constants from abacus_schedule.models import Schedule from abacus_schedule.schemas.schedule import ScheduleDetailSchema def get_schedules_by_target( target_type: str, target_id: str, request_params: dict ) -> Type[response.Response]: """Get all schedules by specified target type and ID. Args: target_type (str): type of target target_id (str): id of the target_type request_params (optional): optional request parameters - include_only_schedules (bool): Flag to return contributor-only schedules """ include_only_schedules = request_params.get('include_only_schedules', False) include_only_schedules = ( include_only_schedules and include_only_schedules.lower() == 'true' ) if target_type not in constants.SCHEDULE_TARGET_TYPE: return response.create_error_response( code='error', message=err_constants.ERROR_MESSAGE_INVALID_SCHEDULE_TARGET.format( target_type=target_type, status=400 ), ) items = Schedule.get_schedules_by_target( target_type, target_id, include_only_schedules ) return response.Response( message=ScheduleDetailSchema(many=True).dump(items), status=200 ) def _validate_conditions( new_conditions: dict, target_type: str, target_id: str, update_schedule_id: int = None, ): """Validate the new conditions for the schedule.""" is_auto_add = new_conditions.get('auto_add', False) if not is_auto_add: return items = Schedule.get_schedules_by_target(target_type, target_id) for item in items: item_conditions = item.conditions or {} item_is_auto_add = item_conditions.get('auto_add') is_update_schedule = item.schedule_id == update_schedule_id if not is_update_schedule and item_is_auto_add: raise ValidationError( err_constants.ERROR_MESSAGE_AUTO_ADD_SCHEDULE_ALREADY_EXISTS.format( target_type=target_type, target_id=target_id ) ) def update_schedule(schedule: dict, **params) -> Type[response.Response]: """Update an existing schedule.""" try: new_conditions = params.get('conditions') or {} _validate_conditions( new_conditions, schedule.target_type, schedule.target_id, schedule.schedule_id, ) schedule.update_attributes(**params) Schedule.commit_changes() return response.Response( message=ScheduleDetailSchema().dump(schedule), status=200 ) except Exception as e: return response.create_error_response('error', str(e), status=400) def create_schedule(**params) -> Type[response.Response]: """Create a new schedule.""" try: new_conditions = params.get('conditions') or {} _validate_conditions( new_conditions, params.get('target_type'), params.get('target_id') ) new_schedule = Schedule.create(**params) return response.Response( message=ScheduleDetailSchema().dump(new_schedule), status=201 ) except Exception as e: return response.create_error_response('error', str(e), status=400)