eliminar loggers

This commit is contained in:
Dulce
2025-12-16 08:22:59 -07:00
parent dad4fa2191
commit a112d746f6

View File

@@ -52,8 +52,6 @@ import uuid
import datetime import datetime
import zipfile import zipfile
from django.db import models from django.db import models
import logging
logger = logging.getLogger(__name__)
def export_model_to_csv(request, model_name, fields, module='datastage', filters=None): def export_model_to_csv(request, model_name, fields, module='datastage', filters=None):
model = apps.get_model(module, model_name) model = apps.get_model(module, model_name)
@@ -192,11 +190,6 @@ class ExportDataStageView(APIView):
if not models_data: if not models_data:
return Response({'error': 'models are required for multiple export'}, status=status.HTTP_400_BAD_REQUEST) return Response({'error': 'models are required for multiple export'}, status=status.HTTP_400_BAD_REQUEST)
logger.info("🚀" * 40)
logger.info("🚀 MODO MÚLTIPLE INICIADO")
logger.info(f"🚀 Request completo: {request.data}")
logger.info(f"🚀 RFC en request: '{request.data.get('globalFilters', {}).get('rfc')}'")
related_keys = self.get_related_keys_from_filters(global_filters, models_data, request.user) related_keys = self.get_related_keys_from_filters(global_filters, models_data, request.user)
if export_type == 'excel': if export_type == 'excel':
@@ -620,20 +613,12 @@ class ExportDataStageView(APIView):
Obtiene patentes, pedimentos y datastages que cumplen EXACTAMENTE con TODOS los filtros globales Obtiene patentes, pedimentos y datastages que cumplen EXACTAMENTE con TODOS los filtros globales
VERSIÓN SIMPLIFICADA - Usa la MISMA lógica que apply_global_filters_to_model VERSIÓN SIMPLIFICADA - Usa la MISMA lógica que apply_global_filters_to_model
""" """
import logging
logger = logging.getLogger(__name__)
related_keys = { related_keys = {
'patentes': set(), 'patentes': set(),
'pedimentos': set(), 'pedimentos': set(),
'datastage_ids': set() 'datastage_ids': set()
} }
logger.info("🔥" * 60)
logger.info("🔥 DEBUG get_related_keys_from_filters - COMPARACIÓN CON SINGULAR")
logger.info(f"🔥 Filtros recibidos: {global_filters}")
logger.info(f"🔥 RFC específico: '{global_filters.get('rfc')}'")
# Si no hay filtros, retornar vacío # Si no hay filtros, retornar vacío
if not any(v for v in global_filters.values() if v not in [None, '']): if not any(v for v in global_filters.values() if v not in [None, '']):
return {} return {}
@@ -642,7 +627,6 @@ class ExportDataStageView(APIView):
for model_data in models_data: for model_data in models_data:
model_name = model_data.get('model') model_name = model_data.get('model')
logger.info(f"\n🔥 PROCESANDO: {model_name}")
try: try:
model = apps.get_model('datastage', model_name) model = apps.get_model('datastage', model_name)
@@ -650,35 +634,23 @@ class ExportDataStageView(APIView):
# ¡USAR LA MISMA FUNCIÓN QUE EN MODO SINGULAR! # ¡USAR LA MISMA FUNCIÓN QUE EN MODO SINGULAR!
filters = self.apply_global_filters_to_model(global_filters, model, user) filters = self.apply_global_filters_to_model(global_filters, model, user)
logger.info(f"🔥 Filtros después de apply_global_filters_to_model: {filters}")
if filters: if filters:
# EJECUTAR CONSULTA - IDÉNTICO A MODO SINGULAR # EJECUTAR CONSULTA - IDÉNTICO A MODO SINGULAR
queryset = model.objects.filter(**filters) queryset = model.objects.filter(**filters)
total = queryset.count() total = queryset.count()
logger.info(f"🔥 Total registros: {total}")
# VERIFICACIÓN ESPECIAL PARA RFC # VERIFICACIÓN ESPECIAL PARA RFC
if 'rfc' in filters: if 'rfc' in filters:
rfc_value = filters['rfc'] rfc_value = filters['rfc']
# Doble verificación: contar registros con ese RFC exacto # Doble verificación: contar registros con ese RFC exacto
rfc_exact_count = queryset.filter(rfc=rfc_value).count() rfc_exact_count = queryset.filter(rfc=rfc_value).count()
logger.info(f"🔥 Verificación RFC: {rfc_exact_count}/{total} registros tienen RFC '{rfc_value}'")
if rfc_exact_count != total: if rfc_exact_count != total:
logger.error(f"🔥🔥🔥 ERROR: Hay {total - rfc_exact_count} registros con OTRO RFC!")
# Mostrar RFCs diferentes
try: try:
other_rfcs = queryset.exclude(rfc=rfc_value).values_list('rfc', flat=True).distinct()[:5] other_rfcs = queryset.exclude(rfc=rfc_value).values_list('rfc', flat=True).distinct()[:5]
logger.error(f"🔥🔥🔥 RFCs diferentes encontrados: {list(other_rfcs)}")
except: except:
pass pass
# Mostrar SQL
logger.info(f"🔥 SQL generada: {str(queryset.query)}")
# Obtener registros # Obtener registros
records = queryset.values('patente', 'pedimento', 'datastage_id') records = queryset.values('patente', 'pedimento', 'datastage_id')
all_records_with_filters.extend(list(records)) all_records_with_filters.extend(list(records))
@@ -697,24 +669,16 @@ class ExportDataStageView(APIView):
if record.get('datastage_id'): if record.get('datastage_id'):
related_keys['datastage_ids'].add(record['datastage_id']) related_keys['datastage_ids'].add(record['datastage_id'])
logger.info(f"\n🔥 Related_keys encontradas:")
logger.info(f"🔥 Patentes: {len(related_keys['patentes'])}")
logger.info(f"🔥 Pedimentos: {len(related_keys['pedimentos'])}")
return {k: list(v) for k, v in related_keys.items() if v} return {k: list(v) for k, v in related_keys.items() if v}
def apply_global_filters_to_model(self, global_filters, model, user): def apply_global_filters_to_model(self, global_filters, model, user):
""" """
Aplica filtros globales - VERSIÓN CORREGIDA CON UUID Aplica filtros globales - VERSIÓN CORREGIDA CON UUID
""" """
import logging
logger = logging.getLogger(__name__)
filters = {} filters = {}
model_fields = [f.name for f in model._meta.get_fields()] model_fields = [f.name for f in model._meta.get_fields()]
logger.info(f"\n🔍 apply_global_filters_to_model - Modelo: {model.__name__}")
# ORGANIZACIÓN - Manejar como UUID # ORGANIZACIÓN - Manejar como UUID
org_value = global_filters.get('organizacion') org_value = global_filters.get('organizacion')
if org_value and org_value != '' and 'organizacion' in model_fields: if org_value and org_value != '' and 'organizacion' in model_fields:
@@ -726,21 +690,16 @@ class ExportDataStageView(APIView):
import uuid import uuid
org_uuid = uuid.UUID(org_value) org_uuid = uuid.UUID(org_value)
filters['organizacion_id'] = org_uuid filters['organizacion_id'] = org_uuid
logger.info(f"✅ Organización como UUID: {org_uuid}")
except Exception as e: except Exception as e:
logger.error(f"❌ Error convirtiendo organizacion a UUID: {e}")
# Fallback: dejar como string (puede no funcionar) # Fallback: dejar como string (puede no funcionar)
filters['organizacion_id'] = org_value filters['organizacion_id'] = org_value
logger.warning(f"⚠️ Organización como string: {org_value}")
else: # Es CharField else: # Es CharField
filters['organizacion'] = org_value filters['organizacion'] = org_value
logger.info(f"✅ Organización como string: {org_value}")
# RFC - Manejar normalmente # RFC - Manejar normalmente
rfc_value = global_filters.get('rfc') rfc_value = global_filters.get('rfc')
if rfc_value and rfc_value != '' and 'rfc' in model_fields: if rfc_value and rfc_value != '' and 'rfc' in model_fields:
filters['rfc'] = rfc_value filters['rfc'] = rfc_value
logger.info(f"✅ RFC: {rfc_value}")
# PATENTE # PATENTE
if global_filters.get('patente'): if global_filters.get('patente'):
@@ -758,70 +717,50 @@ class ExportDataStageView(APIView):
if global_filters.get('fecha_pago_hasta'): if global_filters.get('fecha_pago_hasta'):
filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta'] filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta']
logger.info(f"🔍 Filtros finales: {filters}")
return filters return filters
def apply_related_filters(self, global_filters, model, related_keys, user): def apply_related_filters(self, global_filters, model, related_keys, user):
filters = {} filters = {}
model_fields = [f.name for f in model._meta.get_fields()] model_fields = [f.name for f in model._meta.get_fields()]
logger.info(f"\n🎯 apply_related_filters para {model.__name__}")
# 🔥 PRIMERO: APLICAR FILTROS GLOBALES BASE (RFC, ORGANIZACIÓN, FECHAS)
# Estos son los filtros que SIEMPRE deben aplicarse
# 1. Organización # 1. Organización
if 'organizacion' in model_fields and global_filters.get('organizacion'): if 'organizacion' in model_fields and global_filters.get('organizacion'):
filters['organizacion'] = global_filters['organizacion'] filters['organizacion'] = global_filters['organizacion']
logger.info(f"✅ Filtro organizacion: {global_filters.get('organizacion')}")
# 2. RFC (¡ESTO ES LO QUE FALTA!) # 2. RFC (¡ESTO ES LO QUE FALTA!)
if 'rfc' in model_fields and global_filters.get('rfc'): if 'rfc' in model_fields and global_filters.get('rfc'):
filters['rfc'] = global_filters['rfc'] filters['rfc'] = global_filters['rfc']
logger.info(f"✅ Filtro RFC: {global_filters.get('rfc')}")
# 3. Fechas (SIEMPRE se aplican) # 3. Fechas (SIEMPRE se aplican)
if 'fecha_pago_real' in model_fields: if 'fecha_pago_real' in model_fields:
if global_filters.get('fecha_pago_desde'): if global_filters.get('fecha_pago_desde'):
filters['fecha_pago_real__gte'] = global_filters['fecha_pago_desde'] filters['fecha_pago_real__gte'] = global_filters['fecha_pago_desde']
logger.info(f"✅ Fecha desde: {global_filters.get('fecha_pago_desde')}")
if global_filters.get('fecha_pago_hasta'): if global_filters.get('fecha_pago_hasta'):
filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta'] filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta']
logger.info(f"✅ Fecha hasta: {global_filters.get('fecha_pago_hasta')}")
# 🔥 SEGUNDO: Si hay related_keys, AÑADIRLAS a los filtros existentes # 🔥 SEGUNDO: Si hay related_keys, AÑADIRLAS a los filtros existentes
if any(related_keys.values()): if any(related_keys.values()):
logger.info(f"🎯 Añadiendo related_keys a filtros existentes")
# Añadir patentes si existen # Añadir patentes si existen
if related_keys.get('patentes') and 'patente' in model_fields: if related_keys.get('patentes') and 'patente' in model_fields:
filters['patente__in'] = related_keys['patentes'] filters['patente__in'] = related_keys['patentes']
logger.info(f"✅ Filtrando por {len(related_keys['patentes'])} patentes")
# Añadir pedimentos si existen # Añadir pedimentos si existen
if related_keys.get('pedimentos') and 'pedimento' in model_fields: if related_keys.get('pedimentos') and 'pedimento' in model_fields:
filters['pedimento__in'] = related_keys['pedimentos'] filters['pedimento__in'] = related_keys['pedimentos']
logger.info(f"✅ Filtrando por {len(related_keys['pedimentos'])} pedimentos")
# Añadir datastage_ids si existen # Añadir datastage_ids si existen
if related_keys.get('datastage_ids') and 'datastage_id' in model_fields: if related_keys.get('datastage_ids') and 'datastage_id' in model_fields:
filters['datastage_id__in'] = related_keys['datastage_ids'] filters['datastage_id__in'] = related_keys['datastage_ids']
logger.info(f"✅ Filtrando por {len(related_keys['datastage_ids'])} datastage_ids")
# 🔥 TERCERO: Si NO hay related_keys pero hay filtros específicos, añadirlos
else: else:
# Solo patente y pedimento específicos (no listas) # Solo patente y pedimento específicos (no listas)
if 'patente' in model_fields and global_filters.get('patente'): if 'patente' in model_fields and global_filters.get('patente'):
filters['patente'] = global_filters['patente'] filters['patente'] = global_filters['patente']
logger.info(f"✅ Filtro patente específica: {global_filters.get('patente')}")
if 'pedimento' in model_fields and global_filters.get('pedimento'): if 'pedimento' in model_fields and global_filters.get('pedimento'):
filters['pedimento'] = global_filters['pedimento'] filters['pedimento'] = global_filters['pedimento']
logger.info(f"✅ Filtro pedimento específico: {global_filters.get('pedimento')}")
logger.info(f"🎯 Filtros FINALES para {model.__name__}: {filters}")
return filters return filters