feature/capturar errores, evitar duplicados, eliminar manejar nuevas flags para descargar datos de vucem
This commit is contained in:
@@ -100,31 +100,18 @@ class APIRESTController:
|
||||
identifier: str = None, binary_content: bytes = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Guarda un documento VU (request o error). Si ya existe uno del mismo
|
||||
tipo/pedimento/identificador, elimina el anterior y crea el nuevo,
|
||||
evitando duplicados en ejecuciones recurrentes (tarea programada diaria).
|
||||
Guarda un documento VU (request, error o respuesta). Crea PRIMERO el
|
||||
documento nuevo y, solo si se guardó con éxito, elimina los previos del
|
||||
mismo tipo/pedimento/identificador. Así se evitan duplicados en
|
||||
ejecuciones recurrentes sin perder el documento anterior cuando el
|
||||
guardado del nuevo falla (antes se borraba el previo antes del POST).
|
||||
|
||||
identifier: cadena única del documento dentro del pedimento
|
||||
(ej: número de COVE, número de e-document). Se usa como
|
||||
filtro archivo__icontains para distinguir documentos del
|
||||
mismo tipo pertenecientes a distintos COVEs o edocs.
|
||||
"""
|
||||
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) and results:
|
||||
existing_id = results[0].get('id')
|
||||
if existing_id:
|
||||
await self._make_request_async('DELETE', f'record/documents/{existing_id}/')
|
||||
logger.info(f"Documento VU previo eliminado: id={existing_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 await self.post_document(
|
||||
new_document = await self.post_document(
|
||||
soap_response=soap_response,
|
||||
binary_content=binary_content,
|
||||
organizacion=organizacion,
|
||||
@@ -133,6 +120,33 @@ class APIRESTController:
|
||||
document_type=document_type,
|
||||
fuente=fuente,
|
||||
)
|
||||
if not new_document:
|
||||
# POST falló: conservar los documentos previos intactos
|
||||
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 put_procesamiento(self, service_id: int, data: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return await self._make_request_async('PUT', f'customs/procesamientopedimentos/{service_id}/', data=data)
|
||||
|
||||
@@ -135,13 +135,14 @@ class XMLScraper: # Clase me extrae datos de Pedimento
|
||||
def _remesas(self, root: ET.Element) -> bool:
|
||||
"""
|
||||
Método para verificar si el pedimento tiene remesas.
|
||||
Busca identificadores con clave 'RC' (REMESAS DE CONSOLIDADO).
|
||||
|
||||
Busca identificadores con clave 'PC' (PEDIMENTO CONSOLIDADO)
|
||||
o 'RC' (REMESAS DE CONSOLIDADO).
|
||||
|
||||
Args:
|
||||
root: Elemento raíz del XML.
|
||||
|
||||
|
||||
Returns:
|
||||
True si encuentra identificadores con clave 'RC', False en caso contrario.
|
||||
True si encuentra identificadores con clave 'PC' o 'RC', False en caso contrario.
|
||||
"""
|
||||
namespaces = {
|
||||
'ns2': 'http://www.ventanillaunica.gob.mx/pedimentos/ws/oxml/consultarpedimentocompleto',
|
||||
@@ -157,8 +158,8 @@ class XMLScraper: # Clase me extrae datos de Pedimento
|
||||
clave_elem = identificador.find('ns:claveIdentificador/ns:clave', namespaces)
|
||||
clave = clave_elem.text if clave_elem is not None else None
|
||||
|
||||
# Si encontramos una clave 'RC', el pedimento tiene remesas
|
||||
if clave == 'RC':
|
||||
# PC (consolidado) o RC (remesas de consolidado) indican remesas
|
||||
if clave in ('PC', 'RC'):
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
@@ -166,7 +167,7 @@ class XMLScraper: # Clase me extrae datos de Pedimento
|
||||
print(f"Error procesando identificador para remesas: {e}")
|
||||
continue
|
||||
|
||||
print("No se encontraron remesas (sin identificadores RC)")
|
||||
print("No se encontraron remesas (sin identificadores PC/RC)")
|
||||
return False
|
||||
|
||||
def _get_tipo_operacion(self, root: ET.Element) -> str:
|
||||
|
||||
Reference in New Issue
Block a user