import logging import httpx from typing import Dict, Any from fastapi import HTTPException from ..common import create_error_response from core.config import settings logger = logging.getLogger(__name__) async def update_task( task_id: str, message: str, status: str, pedimento_id: str, organizacion_id: str, servicio: int ) -> Dict[str, Any]: """ Actualiza el estado de una tarea existente en el servicio de seguimiento. Args: task_id: ID de la tarea de Celery message: Mensaje descriptivo del nuevo estado de la tarea status: Nuevo estado de la tarea pedimento_id: ID del pedimento asociado organizacion_id: ID de la organización servicio: ID del tipo de servicio (1-9) Returns: Dict con la respuesta del servicio """ try: headers = { "Authorization": f"Token {settings.API_TOKEN}" } # Construir el cuerpo de la petición update_data = { "task_id": task_id, "message": message, "status": status, "pedimento": pedimento_id, "organizacion": organizacion_id, "servicio": servicio } logger.info(f"Actualizando tarea {task_id} con datos: {update_data}") # Django requiere el slash final url = f"{settings.API_URL}/tasks/tasks/{task_id}/" logger.info(f"Actualizando tarea en: {url}") async with httpx.AsyncClient() as client: response = await client.put( url, json=update_data, headers=headers ) if response.status_code == 404: logger.warning(f"Tarea {task_id} no encontrada, intentando crearla...") return await _create_and_update_task( task_id, message, status, pedimento_id, organizacion_id, servicio ) response.raise_for_status() return response.json() except httpx.HTTPError as e: logger.error(f"Error al actualizar tarea {task_id}: {str(e)}") raise HTTPException( status_code=500, detail=create_error_response( message="Error al actualizar la tarea", errors=[str(e)], metadata={ "task_id": task_id, "status": status } ) ) except Exception as e: logger.error(f"Error inesperado al actualizar tarea {task_id}: {str(e)}") raise HTTPException( status_code=500, detail=create_error_response( message="Error inesperado al actualizar la tarea", errors=[str(e)], metadata={"task_id": task_id} ) ) async def _create_and_update_task( task_id: str, message: str, status: str, pedimento_id: str, organizacion_id: str, servicio: int ) -> Dict[str, Any]: """ Función interna para crear una tarea y luego actualizarla. """ try: # Primero crear la tarea logger.info(f"Creando tarea {task_id} antes de actualizar") headers = { "Authorization": f"Token {settings.API_TOKEN}" } create_data = { "task_id": task_id, "message": message, "status": status, "pedimento": pedimento_id, "organizacion": organizacion_id, "servicio": servicio } async with httpx.AsyncClient() as client: # Crear la tarea create_response = await client.post( f"{settings.API_URL}/tasks/tasks/", json=create_data, headers=headers ) create_response.raise_for_status() logger.info(f"Tarea {task_id} creada exitosamente") # Actualizar la tarea recién creada url = f"{settings.API_URL}/tasks/tasks/{task_id}/" update_response = await client.put( url, json=create_data, headers=headers ) update_response.raise_for_status() logger.info(f"Tarea {task_id} actualizada exitosamente después de crear") return update_response.json() except httpx.HTTPError as e: logger.error(f"Error al crear/actualizar tarea {task_id}: {str(e)}") raise HTTPException( status_code=500, detail=create_error_response( message="Error al crear la tarea", errors=[str(e)], metadata={ "task_id": task_id, "status": status } ) ) async def register_task( task_id: str, message: str, status: str, pedimento_id: str, organizacion_id: str, servicio: int ) -> Dict[str, Any]: """ Registra una tarea en el servicio de seguimiento. Args: task_id: ID de la tarea de Celery message: Mensaje descriptivo de la tarea status: Estado actual de la tarea pedimento_id: ID del pedimento asociado organizacion_id: ID de la organización servicio: ID del tipo de servicio 1: Estado de pedimento 2: Listado de pedimentos 3: Pedimento Completo 4: Pedimento Partidas 5: Pedimento Remesas 6: Acuse 7: EDocument 8: Cove 9: Acuse Cove Returns: Dict con la respuesta del servicio """ try: headers = { "Authorization": f"Token {settings.API_TOKEN}" } async with httpx.AsyncClient() as client: response = await client.post( f"{settings.API_URL}/tasks/tasks/", json={ "task_id": task_id, "message": message, "status": status, "pedimento": pedimento_id, "organizacion": organizacion_id, "servicio": servicio }, headers=headers ) response.raise_for_status() return response.json() except httpx.HTTPError as e: logger.error(f"Error al registrar tarea {task_id}: {str(e)}") raise HTTPException( status_code=500, detail=create_error_response( message="Error al registrar la tarea", errors=[str(e)], metadata={ "task_id": task_id, "status": status, "pedimento": pedimento_id } ) ) except Exception as e: logger.error(f"Error inesperado al registrar tarea {task_id}: {str(e)}") raise HTTPException( status_code=500, detail=create_error_response( message="Error inesperado al registrar la tarea", errors=[str(e)], metadata={"task_id": task_id} ) )