correccion-reportes #9
@@ -52,8 +52,6 @@ import uuid
|
||||
import datetime
|
||||
import zipfile
|
||||
from django.db import models
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def export_model_to_csv(request, model_name, fields, module='datastage', filters=None):
|
||||
model = apps.get_model(module, model_name)
|
||||
@@ -192,11 +190,6 @@ class ExportDataStageView(APIView):
|
||||
if not models_data:
|
||||
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)
|
||||
|
||||
if export_type == 'excel':
|
||||
@@ -620,20 +613,12 @@ class ExportDataStageView(APIView):
|
||||
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
|
||||
"""
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
related_keys = {
|
||||
'patentes': set(),
|
||||
'pedimentos': 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
|
||||
if not any(v for v in global_filters.values() if v not in [None, '']):
|
||||
return {}
|
||||
@@ -642,7 +627,6 @@ class ExportDataStageView(APIView):
|
||||
|
||||
for model_data in models_data:
|
||||
model_name = model_data.get('model')
|
||||
logger.info(f"\n🔥 PROCESANDO: {model_name}")
|
||||
|
||||
try:
|
||||
model = apps.get_model('datastage', model_name)
|
||||
@@ -650,35 +634,23 @@ class ExportDataStageView(APIView):
|
||||
# ¡USAR LA MISMA FUNCIÓN QUE EN MODO SINGULAR!
|
||||
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:
|
||||
# EJECUTAR CONSULTA - IDÉNTICO A MODO SINGULAR
|
||||
queryset = model.objects.filter(**filters)
|
||||
total = queryset.count()
|
||||
|
||||
logger.info(f"🔥 Total registros: {total}")
|
||||
|
||||
# VERIFICACIÓN ESPECIAL PARA RFC
|
||||
if 'rfc' in filters:
|
||||
rfc_value = filters['rfc']
|
||||
# Doble verificación: contar registros con ese RFC exacto
|
||||
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:
|
||||
logger.error(f"🔥🔥🔥 ERROR: Hay {total - rfc_exact_count} registros con OTRO RFC!")
|
||||
|
||||
# Mostrar RFCs diferentes
|
||||
try:
|
||||
other_rfcs = queryset.exclude(rfc=rfc_value).values_list('rfc', flat=True).distinct()[:5]
|
||||
logger.error(f"🔥🔥🔥 RFCs diferentes encontrados: {list(other_rfcs)}")
|
||||
except:
|
||||
pass
|
||||
|
||||
# Mostrar SQL
|
||||
logger.info(f"🔥 SQL generada: {str(queryset.query)}")
|
||||
|
||||
# Obtener registros
|
||||
records = queryset.values('patente', 'pedimento', 'datastage_id')
|
||||
all_records_with_filters.extend(list(records))
|
||||
@@ -697,24 +669,16 @@ class ExportDataStageView(APIView):
|
||||
if record.get('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}
|
||||
|
||||
def apply_global_filters_to_model(self, global_filters, model, user):
|
||||
"""
|
||||
Aplica filtros globales - VERSIÓN CORREGIDA CON UUID
|
||||
"""
|
||||
import logging
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
filters = {}
|
||||
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
|
||||
org_value = global_filters.get('organizacion')
|
||||
if org_value and org_value != '' and 'organizacion' in model_fields:
|
||||
@@ -726,21 +690,16 @@ class ExportDataStageView(APIView):
|
||||
import uuid
|
||||
org_uuid = uuid.UUID(org_value)
|
||||
filters['organizacion_id'] = org_uuid
|
||||
logger.info(f"✅ Organización como UUID: {org_uuid}")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Error convirtiendo organizacion a UUID: {e}")
|
||||
# Fallback: dejar como string (puede no funcionar)
|
||||
filters['organizacion_id'] = org_value
|
||||
logger.warning(f"⚠️ Organización como string: {org_value}")
|
||||
else: # Es CharField
|
||||
filters['organizacion'] = org_value
|
||||
logger.info(f"✅ Organización como string: {org_value}")
|
||||
|
||||
# RFC - Manejar normalmente
|
||||
rfc_value = global_filters.get('rfc')
|
||||
if rfc_value and rfc_value != '' and 'rfc' in model_fields:
|
||||
filters['rfc'] = rfc_value
|
||||
logger.info(f"✅ RFC: {rfc_value}")
|
||||
|
||||
# PATENTE
|
||||
if global_filters.get('patente'):
|
||||
@@ -758,70 +717,50 @@ class ExportDataStageView(APIView):
|
||||
if global_filters.get('fecha_pago_hasta'):
|
||||
filters['fecha_pago_real__lte'] = global_filters['fecha_pago_hasta']
|
||||
|
||||
logger.info(f"🔍 Filtros finales: {filters}")
|
||||
|
||||
return filters
|
||||
|
||||
def apply_related_filters(self, global_filters, model, related_keys, user):
|
||||
filters = {}
|
||||
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
|
||||
if 'organizacion' in model_fields and global_filters.get('organizacion'):
|
||||
filters['organizacion'] = global_filters['organizacion']
|
||||
logger.info(f"✅ Filtro organizacion: {global_filters.get('organizacion')}")
|
||||
|
||||
# 2. RFC (¡ESTO ES LO QUE FALTA!)
|
||||
if 'rfc' in model_fields and global_filters.get('rfc'):
|
||||
filters['rfc'] = global_filters['rfc']
|
||||
logger.info(f"✅ Filtro RFC: {global_filters.get('rfc')}")
|
||||
|
||||
# 3. Fechas (SIEMPRE se aplican)
|
||||
if 'fecha_pago_real' in model_fields:
|
||||
if global_filters.get('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'):
|
||||
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
|
||||
if any(related_keys.values()):
|
||||
logger.info(f"🎯 Añadiendo related_keys a filtros existentes")
|
||||
|
||||
# Añadir patentes si existen
|
||||
if related_keys.get('patentes') and 'patente' in model_fields:
|
||||
filters['patente__in'] = related_keys['patentes']
|
||||
logger.info(f"✅ Filtrando por {len(related_keys['patentes'])} patentes")
|
||||
|
||||
# Añadir pedimentos si existen
|
||||
if related_keys.get('pedimentos') and 'pedimento' in model_fields:
|
||||
filters['pedimento__in'] = related_keys['pedimentos']
|
||||
logger.info(f"✅ Filtrando por {len(related_keys['pedimentos'])} pedimentos")
|
||||
|
||||
# Añadir datastage_ids si existen
|
||||
if related_keys.get('datastage_ids') and 'datastage_id' in model_fields:
|
||||
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:
|
||||
# Solo patente y pedimento específicos (no listas)
|
||||
if 'patente' in model_fields and global_filters.get('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'):
|
||||
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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user