From 95b63f32b52b9dac1a775857d7ad4eb80f0bc1e1 Mon Sep 17 00:00:00 2001 From: marcos Date: Wed, 24 Jun 2026 15:26:41 -0600 Subject: [PATCH] fix: peticiones.py usa pedimento_app + post_or_update_document (T2025-09-004) El stack viejo de descarga (utils/peticiones.py, via api_v1 + signal en backend) armaba el nombre con campos crudos en vez de pedimento_app (vu_EDC, app 042_240_...) y posteaba con post_document (sin reemplazar) -> documentos sin ligar la FK y partidas duplicadas. Las 8 funciones get_soap_* (pedimento_completo, remesas, partidas, acuse, acuseCOVE, estado, edocument, cove) ahora arman el nombre con pedimento_app (identico a api_v2) y postean con post_or_update_document + identifier. Corrige tambien el prefijo vu_EDC -> vu_ED. Co-Authored-By: Claude Opus 4.8 (1M context) --- CHANGELOG.md | 37 +++++++++++++++++++ controllers/RESTController.py | 53 ++++++++++++++++++++++++++- utils/peticiones.py | 68 +++++++++++++++++++++++------------ 3 files changed, 134 insertions(+), 24 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..cdff801 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,37 @@ +# Changelog — EFC Microservice + +Historial de cambios por ticket (más reciente arriba). Reglas del flujo en `../CLAUDE.md`. + +## T2025-09-004 — Nomenclatura/dedup de descargas (stack legacy `peticiones.py`) +- **Fecha:** 2026-06-24 +- **Tipo:** fix +- **Repos:** microservice (lo dispara un signal en backend; ver `backend/CHANGELOG.md`) +- **Branch:** `feature/T2025-09-004` · **PR:** (pendiente de aceptación manual) +- **Rastreo (root cause):** + - Dos stacks de descarga corrían en paralelo. El NUEVO `api/api_v2/modules/*` usa + `pedimento_app` + `post_or_update_document` (liga la FK y reemplaza, no duplica). El + VIEJO `utils/peticiones.py` armaba el nombre con campos crudos + `{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}` (≠ `pedimento_app`), + usaba prefijo `vu_EDC` (no `vu_ED`) y posteaba con `post_document` (sin reemplazar → duplicaba). + - Disparador: el backend, al crear Pedimento/Cove/EDocument (p.ej. al cargar un datastage), + ejecuta el signal `api/customs/signals/procesamiento.py` (post_save) → tareas de + `api.customs.tasks.microservice` → `api_v1` → `peticiones.py`. En paralelo, el Celery beat + `microservice_v2.process_all_organizations` corre el stack v2. + - Síntoma observado (pedimento `5d9c6fb1...`, hoy): cada partida con 2 docs (uno por stack); + los edoc/acuse del stack viejo con app anómalo (`042_240_3452_6000382`) y `vu_EDC` → no + ligaban la FK; partidas "descargadas dos veces". +- **Fix:** `utils/peticiones.py` — las 8 funciones de descarga + (`get_soap_pedimento_completo`, `get_soap_remesas`, `get_soap_partidas`, `get_soap_acuse`, + `get_soap_acuseCOVE`, `get_estado_pedimento`, `get_soap_edocument`, `get_soap_cove`) arman el + nombre con `pedimento_app` (idéntico a api_v2) y postean con `post_or_update_document` (con + `identifier` para partida/cove/edoc/acuses) → nombres correctos, FK ligada en `Document.save()`, + sin duplicar. Corrige también el prefijo `vu_EDC` → `vu_ED`. Como `peticiones.py` usa el + `APIController` (que no tenía ese método), se agregó `post_or_update_document` a `APIController` + en `controllers/RESTController.py`. +- **Diseño / no-duplicidad:** el alcance del beat v2 (`ejecutar_basicos_organizacion`: solo + coves/edocs/acuses) es **intencional**; partidas/remesas/PC se procesan por el signal. La + no-duplicidad NO depende de unificar los stacks: con ambos flujos usando el MISMO nombre + (`pedimento_app`) + `post_or_update_document` con el mismo `identifier`, el segundo flujo en + correr **reemplaza** el documento del primero → no quedan filas duplicadas. (Residual: doble + descarga de coves/edocs por los dos flujos —perf, no duplicidad—; y una carrera de + concurrencia exacta se auto-corrige en la siguiente corrida del beat.) diff --git a/controllers/RESTController.py b/controllers/RESTController.py index bde5000..13a3da6 100644 --- a/controllers/RESTController.py +++ b/controllers/RESTController.py @@ -340,10 +340,61 @@ class APIController: """ return await self._make_request_async('PUT', f'customs/pedimentos/{pedimento_id}/', data=data) + async def post_or_update_document( + self, soap_response=None, organizacion: str = None, + pedimento: str = None, file_name: str = None, + document_type: int = None, fuente: int = 2, + identifier: str = None, binary_content: bytes = None, + ) -> Dict[str, Any]: + """ + Guarda un documento VU creando PRIMERO el nuevo y, solo si se guardó con + éxito, eliminando los previos del mismo tipo/pedimento/identificador. Así + se evitan duplicados en ejecuciones recurrentes (T2025-09-004). Mismo + comportamiento que la otra clase del módulo; aquí lo usa peticiones.py. + + identifier: cadena única del documento dentro del pedimento (número de + cove / e-document) usada como filtro archivo__icontains. + """ + new_document = await self.post_document( + soap_response=soap_response, + binary_content=binary_content, + organizacion=organizacion, + pedimento=pedimento, + file_name=file_name, + document_type=document_type, + fuente=fuente, + ) + if not new_document: + logger.error(f"post_or_update_document: no se guardó el documento nuevo (document_type={document_type}, identifier={identifier}); se conservan los previos") + return new_document + + new_id = new_document.get('id') if isinstance(new_document, dict) else None + if not new_id: + logger.warning(f"post_or_update_document: respuesta sin id, se omite limpieza de previos (document_type={document_type}, identifier={identifier})") + return new_document + + try: + query = f'record/documents/?pedimento={pedimento}&document_type={document_type}' + if identifier: + query += f'&archivo__icontains={identifier}' + existing = await self._make_request_async('GET', query) + if existing: + results = existing.get('results', existing) if isinstance(existing, dict) else existing + if isinstance(results, list): + for previous in results: + previous_id = previous.get('id') + if previous_id and previous_id != new_id: + await self._make_request_async('DELETE', f'record/documents/{previous_id}/') + logger.info(f"Documento VU previo eliminado: id={previous_id}, document_type={document_type}, identifier={identifier}") + except Exception as e: + logger.warning(f"No se pudo verificar/eliminar documento VU existente (document_type={document_type}, identifier={identifier}): {e}") + + return new_document + async def post_document(self, soap_response=None, organizacion: str = None, pedimento: str = None, file_name: str = None, document_type: int = 2, binary_content: bytes = None, fuente: int = 2) -> Dict[str, Any]: """ Método para enviar documentos (XML, PDF, etc.) a la API. - + Args: soap_response: Respuesta del servicio SOAP (para archivos XML) organizacion: UUID de la organización (requerido) diff --git a/utils/peticiones.py b/utils/peticiones.py index 378c5f4..86797b9 100644 --- a/utils/peticiones.py +++ b/utils/peticiones.py @@ -301,14 +301,17 @@ async def get_soap_pedimento_completo(credenciales, response_service, soap_contr tipo_operacion = data.get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_PC_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}.xml" + # T2025-09-004: nombre canónico con pedimento_app (igual que api_v2) y + # post_or_update_document para reemplazar el previo en vez de duplicar. + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_PC_{pedimento_app}.xml" # Enviar el documento XML como respuesta - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( soap_response=soap_response, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], file_name=_file_name, - document_type=2, + document_type=2, ) data['organizacion'] = response_service['organizacion'] @@ -392,9 +395,11 @@ async def get_soap_remesas(credenciales, response_service, soap_controller): # T tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_RM_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}.xml" + # T2025-09-004: pedimento_app + post_or_update_document (no duplicar). + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_RM_{pedimento_app}.xml" - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( soap_response=soap_response, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], @@ -481,7 +486,9 @@ async def get_soap_partidas(credenciales, response_service, soap_controller, par tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_PT_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}_{partida}.xml" + # T2025-09-004: pedimento_app (igual que api_v2) en lugar de campos crudos. + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_PT_{pedimento_app}_{partida}.xml" # Aqui entra proceso de alonso @@ -497,12 +504,13 @@ async def get_soap_partidas(credenciales, response_service, soap_controller, par # 4. Generar una respues # Enviar el documento XML como respuesta - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( soap_response=soap_response, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], file_name=_file_name, - document_type=1 + document_type=1, + identifier=f"_PT_{pedimento_app}_{partida}_", ) @@ -603,16 +611,19 @@ async def get_soap_acuse(credenciales, response_service, soap_controller, edocum no_partidas = response_service['pedimento'].get('numero_partidas', 0) tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_AC_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}_{edocument['numero_edocument']}.pdf" - + # T2025-09-004: pedimento_app + post_or_update_document (no duplicar). + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_AC_{pedimento_app}_{edocument['numero_edocument']}.pdf" + # Enviar el documento PDF usando binary_content logger.info(f"Enviando documento PDF: {_file_name} ({len(pdf_bytes)} bytes)") - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( binary_content=pdf_bytes, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], file_name=_file_name, - document_type=4 + document_type=4, + identifier=edocument['numero_edocument'], ) return { "servicio": response_service, @@ -710,16 +721,19 @@ async def get_soap_acuseCOVE(credenciales, response_service, soap_controller, co no_partidas = response_service['pedimento'].get('numero_partidas', 0) tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_AC_COVE_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}_{cove['numero_cove']}.pdf" + # T2025-09-004: pedimento_app + post_or_update_document (no duplicar). + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_AC_COVE_{pedimento_app}_{cove['numero_cove']}.pdf" # Enviar el documento PDF usando binary_content logger.info(f"Enviando documento PDF: {_file_name} ({len(pdf_bytes)} bytes)") - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( binary_content=pdf_bytes, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], file_name=_file_name, - document_type=7 + document_type=7, + identifier=cove['numero_cove'], ) return { "servicio": response_service, @@ -781,9 +795,11 @@ async def get_estado_pedimento(credenciales, response_service, soap_controller): tipo_operacion = data.get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_EP_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}.xml" + # T2025-09-004: pedimento_app + post_or_update_document (no duplicar). + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_EP_{pedimento_app}.xml" # Enviar el documento XML como respuesta - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( soap_response=soap_response, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], @@ -884,16 +900,19 @@ async def get_soap_edocument(credenciales, response_service, soap_controller, ed no_partidas = response_service['pedimento'].get('numero_partidas', 0) tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_EDC_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}_{edocument['numero_edocument']}.pdf" + # T2025-09-004: prefijo vu_ED (no vu_EDC) + pedimento_app + post_or_update_document. + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_ED_{pedimento_app}_{edocument['numero_edocument']}.pdf" # Enviar el documento PDF usando binary_content logger.info(f"Enviando documento PDF: {_file_name} ({len(pdf_bytes)} bytes)") - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( binary_content=pdf_bytes, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], file_name=_file_name, - document_type=5 + document_type=5, + identifier=edocument['numero_edocument'], ) return { "servicio": response_service, @@ -1000,14 +1019,17 @@ async def get_soap_cove(credenciales, response_service, soap_controller, cove, i tipo_operacion = response_service['pedimento'].get('tipo_operacion', 'N/A') pedimento = response_service['pedimento'].get('pedimento', 'N/A') - _file_name = f"vu_COVE_{remesas}{no_partidas}{tipo_operacion}_{aduana}_{patente}_{pedimento}_{cove['numero_cove']}.xml" + # T2025-09-004: pedimento_app + post_or_update_document (no duplicar). + pedimento_app = response_service['pedimento'].get('pedimento_app', 'N/A') + _file_name = f"vu_COVE_{pedimento_app}_{cove['numero_cove']}.xml" - document_response = await rest_controller.post_document( + document_response = await rest_controller.post_or_update_document( soap_response=soap_response, organizacion=response_service['organizacion'], pedimento=response_service['pedimento']['id'], file_name=_file_name, - document_type=8, + document_type=8, + identifier=cove['numero_cove'], ) return {