"""Task-related logic.""" from oto import response from availability.connectors import loggly from availability.constants import models from availability.models import task from availability.models import task_log logger = loggly.get_current_logger() def reset_stuck_tasks(store_id, **kwargs): """Reset tasks that are stuck in certain state or failed. Any extra kwargs are passed to get_failed_tasks(). Args: store_id (int): ID of the store for which to reset stuck tasks. Returns: oto.Response: successful Response with empty message on success, error response on failure. """ logger.info('Resetting stuck tasks') params = ( ( task.get_failed_tasks, kwargs, models.TASK_LOG_TYPE_ADD_FAILED, 'Reset status of the failed task'), ( task.get_stuck_tasks, {'task_status': models.TASK_STATUS_IN_QUEUE}, models.TASK_LOG_TYPE_ADD_STUCK, 'Reset status of the task stuck in queue' ), ( task.get_stuck_tasks, {'task_status': models.TASK_STATUS_PROCESSING}, models.TASK_LOG_TYPE_ADD_STUCK, 'Reset status of the task stuck in processing state' ), ) for fetch_func, extra_kwargs, message_type, message in params: tasks_response = fetch_func(store_id=store_id, **extra_kwargs) if not tasks_response: return tasks_response tasks_list = tasks_response.message for row in tasks_list: change_status_response = task.change_status( row.product_in_store_id, models.TASK_STATUS_OK) if not change_status_response: return change_status_response task_log.bulk_create_task_log( task_ids=[row.task_id for row in tasks_list], message_type=message_type, message=message) return response.Response()