feature/pedimento completo carga remesas, coves, edocs y acuses y aparte descarga sus documentos, se corrigieron las formulas de remesas, acuse y e documents para permitir la correcta descarga de susdocumentos y se aseguro que el status sea el correcto
This commit is contained in:
@@ -64,12 +64,12 @@ async def obtener_remesa(**kwargs) -> Dict[str, Any]:
|
||||
try:
|
||||
|
||||
file_name_request = f"vu_RM_{pedimento_data.get('pedimento_app', 'unknown')}_REQUEST.xml"
|
||||
document_response = await remesa_rest_controller.post_document(
|
||||
document_response = await remesa_rest_controller.post_or_update_document(
|
||||
soap_response=soap_xml,
|
||||
organizacion=pedimento_data.get('organizacion'),
|
||||
pedimento=pedimento_data.get('id'),
|
||||
file_name=file_name_request,
|
||||
document_type=15,
|
||||
document_type=15,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -90,12 +90,12 @@ async def obtener_remesa(**kwargs) -> Dict[str, Any]:
|
||||
if soap_error(soap_response):
|
||||
|
||||
file_name = f"vu_RM_{pedimento_data.get('pedimento_app', 'unknown')}_ERROR.xml"
|
||||
document_response = await remesa_rest_controller.post_document(
|
||||
document_response = await remesa_rest_controller.post_or_update_document(
|
||||
soap_response=soap_response,
|
||||
organizacion=pedimento_data.get('organizacion'),
|
||||
pedimento=pedimento_data.get('id'),
|
||||
file_name=file_name,
|
||||
document_type=16,
|
||||
document_type=16,
|
||||
)
|
||||
|
||||
# Aquí necesitamos extraer el mensaje de error real
|
||||
@@ -134,12 +134,12 @@ async def obtener_remesa(**kwargs) -> Dict[str, Any]:
|
||||
# Enviar documento
|
||||
try:
|
||||
|
||||
document_response = await remesa_rest_controller.post_document(
|
||||
document_response = await remesa_rest_controller.post_or_update_document(
|
||||
soap_response=soap_response,
|
||||
organizacion=pedimento_data.get('organizacion'),
|
||||
pedimento=pedimento_data.get('id'),
|
||||
file_name=file_name,
|
||||
document_type=5,
|
||||
document_type=3,
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
@@ -149,12 +149,14 @@ async def obtener_remesa(**kwargs) -> Dict[str, Any]:
|
||||
# Extraer datos del XML
|
||||
try:
|
||||
remesas_data = remesa_xml_scraper.extract_remesas(soap_response.text)
|
||||
|
||||
logger.info(
|
||||
f"Remesas extraídas para pedimento {pedimento_data.get('pedimento_app')}: "
|
||||
f"{len(remesas_data)} COVEs encontrados → {remesas_data}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error al extraer datos XML: {e}")
|
||||
raise HTTPException(status_code=500, detail="Error al procesar respuesta XML")
|
||||
|
||||
|
||||
|
||||
logger.info(f"Remesa procesada exitosamente: {pedimento_data.get('pedimento')}")
|
||||
|
||||
return create_service_response(
|
||||
@@ -202,14 +204,16 @@ async def post_remesa_data(**kwargs) -> Dict[str, Any]:
|
||||
# Obtener datos del servicio web
|
||||
try:
|
||||
ws_data = await obtener_remesa(**kwargs)
|
||||
result["documento"] = ws_data.get("documento", None)
|
||||
xml_content = ws_data.get('xml_content', {})
|
||||
# obtener_remesa devuelve create_service_response → los datos están bajo 'data'
|
||||
ws_data_content = ws_data.get('data', {})
|
||||
result["documento"] = ws_data_content.get("documento", None)
|
||||
xml_content = ws_data_content.get('xml_content', [])
|
||||
result["xml_content"] = xml_content
|
||||
|
||||
|
||||
if not xml_content:
|
||||
logger.warning("No se obtuvo contenido XML del servicio web")
|
||||
logger.warning("No se obtuvo contenido XML del servicio web (lista de remesas vacía)")
|
||||
return result
|
||||
|
||||
|
||||
except HTTPException:
|
||||
raise # Re-lanzar HTTPExceptions
|
||||
except Exception as e:
|
||||
@@ -259,55 +263,61 @@ async def _process_coves_safely(kwargs: Dict[str, Any], xml_content) -> Optional
|
||||
|
||||
async def _post_coves(pedimento_data: Dict[str, Any], coves: List[Dict[str, str]]) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Envía COVEs al sistema REST.
|
||||
|
||||
Args:
|
||||
pedimento_data: Datos del pedimento
|
||||
coves: Lista de diccionarios con datos de COVE (comprobanteVE, remesaAgente, remesaSA)
|
||||
|
||||
Returns:
|
||||
Lista de respuestas exitosas
|
||||
|
||||
Raises:
|
||||
HTTPException: Si no se pudo procesar ningún COVE
|
||||
Crea COVEs en el sistema REST usando patrón get-or-create para evitar duplicados.
|
||||
Si el COVE ya existe (creado por pedimento completo u otra remesa), lo reutiliza.
|
||||
"""
|
||||
if not coves:
|
||||
return []
|
||||
|
||||
|
||||
responses = []
|
||||
errors = []
|
||||
|
||||
|
||||
for cove in coves:
|
||||
# Extraer el número de COVE del diccionario
|
||||
numero_cove = cove.get('comprobanteVE')
|
||||
if not numero_cove:
|
||||
logger.warning(f"COVE sin comprobanteVE encontrado: {cove}")
|
||||
continue
|
||||
|
||||
document_data = {
|
||||
'numero_cove': numero_cove,
|
||||
'organizacion': pedimento_data.get('organizacion'),
|
||||
'pedimento': pedimento_data.get('id')
|
||||
}
|
||||
|
||||
try:
|
||||
# Verificar si el COVE ya existe antes de intentar crearlo
|
||||
existing = await remesa_rest_controller._make_request_async(
|
||||
'GET', f'customs/coves/?numero_cove={numero_cove}'
|
||||
)
|
||||
if existing:
|
||||
results = existing.get('results', existing) if isinstance(existing, dict) else existing
|
||||
if isinstance(results, list) and results:
|
||||
logger.info(f"COVE {numero_cove} ya existe (id={results[0].get('id')}), omitiendo creación")
|
||||
responses.append(results[0])
|
||||
continue
|
||||
|
||||
# No existe → crear
|
||||
document_data = {
|
||||
'numero_cove': numero_cove,
|
||||
'organizacion': pedimento_data.get('organizacion'),
|
||||
'pedimento': pedimento_data.get('id'),
|
||||
}
|
||||
response = await remesa_rest_controller.post_cove(document_data)
|
||||
if response:
|
||||
responses.append(response)
|
||||
logger.debug(f"COVE {numero_cove} procesado exitosamente")
|
||||
logger.info(f"COVE {numero_cove} creado exitosamente")
|
||||
else:
|
||||
error_msg = f"POST de COVE {numero_cove} devolvió respuesta vacía"
|
||||
logger.warning(error_msg)
|
||||
errors.append(error_msg)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"Error al procesar COVE {numero_cove}: {str(e)}"
|
||||
logger.warning(error_msg)
|
||||
errors.append(error_msg)
|
||||
|
||||
|
||||
if not responses and coves:
|
||||
error_detail = f"No se pudo procesar ningún COVE. Errores: {'; '.join(errors)}"
|
||||
logger.error(error_detail)
|
||||
raise HTTPException(status_code=500, detail=error_detail)
|
||||
|
||||
|
||||
if errors:
|
||||
logger.warning(f"Se procesaron {len(responses)}/{len(coves)} COVEs. Errores: {len(errors)}")
|
||||
|
||||
|
||||
return responses
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user