Marco commited on
Commit
249cc30
·
1 Parent(s): 95441a2

update - generacion categorias

Browse files
frontend/web/modules/api_generator.py CHANGED
@@ -12,7 +12,6 @@ import requests
12
  from typing import Dict, List, Any
13
  import re
14
 
15
-
16
  def show():
17
  st.header("⚡ Generador de API Profesional - E-commerce")
18
 
@@ -121,7 +120,6 @@ def show():
121
 
122
  modules = []
123
 
124
- # EL RESTO DEL CÓDIGO SE MANTIENE IGUAL...
125
  if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
126
  if st.session_state.get('global_df') is not None:
127
  df = st.session_state.global_df
@@ -163,24 +161,6 @@ def show():
163
  'data': df,
164
  'fields': field_config
165
  })
166
-
167
- # ✅✅✅ CORRECCIÓN: AGREGAR MÓDULO USUARIOS AUTOMÁTICAMENTE SOLO PARA "DESDE DATOS CARGADOS"
168
- if include_auth and api_type == "🚀 Desde datos cargados":
169
- # Verificar que no exista ya un módulo 'usuarios' en los módulos que se agregarán
170
- existing_module_names = [m['name'] for m in modules]
171
- if 'usuarios' not in existing_module_names:
172
- modules.append({
173
- 'name': 'usuarios',
174
- 'route': '/api/usuarios',
175
- 'source': 'system', # Nuevo tipo para módulos del sistema
176
- 'type': 'usuarios',
177
- 'record_count': 2, # ← ¡CORREGIDO: SOLO 2 USUARIOS DEL SISTEMA!
178
- '_include_system_users': True, # ✅ CORRECCIÓN: Agregar flag para el generador
179
- 'include_images': False,
180
- 'image_source': None,
181
- 'categorias_seleccionadas': []
182
- })
183
- st.success("✅ Módulo de usuarios creado automáticamente para autenticación JWT")
184
 
185
  # Agregar módulos adicionales para API Mock
186
  if api_type in ["🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"]:
@@ -217,25 +197,7 @@ def show():
217
  with st.expander(f"🎭 Configurar módulo: {module}", expanded=False):
218
  module_name = st.text_input("Nombre:", value=module, key=f"mock_{module}_name")
219
  base_route = st.text_input("Ruta:", value=f"/{module}", key=f"mock_{module}_route")
220
-
221
- # ✅ MEJORA: Slider específico para usuarios con JWT
222
- if module == 'usuarios' and include_auth:
223
- record_count = st.slider(
224
- "Número de registros:",
225
- 3, # ✅ CORRECCIÓN: Mínimo 3 para usuarios
226
- 1000,
227
- 50,
228
- key=f"mock_{module}_count",
229
- help="Total de usuarios incluyendo los 2 del sistema (admin + usuario normal)"
230
- )
231
- else:
232
- record_count = st.slider(
233
- "Número de registros:",
234
- 3, # ✅ CORRECCIÓN: Mínimo 3 para TODOS los módulos
235
- 1000,
236
- 50,
237
- key=f"mock_{module}_count"
238
- )
239
 
240
  # Configuración específica por módulo
241
  if module in ["productos"]:
@@ -274,8 +236,7 @@ def show():
274
  image_source = None
275
  categorias_seleccionadas = []
276
 
277
- # ✅✅✅ CORRECCIÓN: AGREGAR FLAG PARA INCLUIR USUARIOS DEL SISTEMA
278
- module_data = {
279
  'name': module_name,
280
  'route': base_route,
281
  'source': 'mock',
@@ -284,45 +245,8 @@ def show():
284
  'include_images': include_images,
285
  'image_source': image_source,
286
  'categorias_seleccionadas': categorias_seleccionadas
287
- }
288
-
289
- # Si es módulo usuarios y JWT está activado, incluir flag y mostrar breakdown
290
- if module == 'usuarios' and include_auth:
291
- module_data['_include_system_users'] = True
292
- usuarios_mock = max(0, record_count - 2)
293
-
294
- # ✅ MEJORA: Mostrar breakdown visual con métricas
295
- col1, col2, col3 = st.columns(3)
296
- with col1:
297
- st.metric("Total", record_count, help="Total de usuarios que se generarán")
298
- with col2:
299
- st.metric("Sistema", 2, help="Admin + Usuario normal (automáticos)")
300
- with col3:
301
- st.metric("Mock", usuarios_mock, help="Usuarios de prueba generados")
302
-
303
- # ✅ CORRECCIÓN: Mensaje mejorado
304
- if usuarios_mock > 0:
305
- st.info(f"🔐 {record_count} usuarios totales: 2 del sistema + {usuarios_mock} mock")
306
- else:
307
- st.info(f"🔐 {record_count} usuarios totales (solo del sistema)")
308
-
309
- modules.append(module_data)
310
-
311
- # ✅✅✅ CORRECCIÓN: FUSIONAR MÓDULOS USUARIOS DUPLICADOS EN MODO HÍBRIDO
312
- user_modules = [m for m in modules if m['name'] == 'usuarios']
313
- if len(user_modules) > 1:
314
- # Encontrar módulo mock (configurable) y módulo sistema (automático)
315
- mock_user_module = next((m for m in user_modules if m['source'] == 'mock'), None)
316
- system_user_module = next((m for m in user_modules if m['source'] == 'system'), None)
317
-
318
- if mock_user_module and system_user_module:
319
- # ✅ CORRECCIÓN: Los 2 usuarios del sistema YA ESTÁN INCLUIDOS en el total configurado
320
- # Solo fusionar manteniendo el módulo mock y eliminando el sistema
321
- mock_user_module['_include_system_users'] = True # Flag para generador
322
- # Eliminar el módulo sistema
323
- modules = [m for m in modules if not (m['name'] == 'usuarios' and m['source'] == 'system')]
324
- st.info(f"🔍 Módulos usuarios fusionados: {mock_user_module['record_count']} usuarios totales (incluye 2 del sistema)")
325
-
326
  # CONFIGURACIÓN AVANZADA
327
  st.subheader("⚙️ Configuración Avanzada")
328
 
@@ -333,7 +257,7 @@ def show():
333
  rate_limiting = st.checkbox("⏱️ Rate Limiting", value=True)
334
  file_uploads = st.checkbox("📁 Manejo de archivos", value=True)
335
  include_migrations = st.checkbox("🔄 Migraciones Alembic", value=True)
336
- pagination_size = st.slider("Tamaño de paginación:", 3, 100, 25)
337
 
338
  with adv_col2:
339
  logging_level = st.selectbox("Nivel de logging:", ["DEBUG", "INFO", "WARNING", "ERROR"])
@@ -417,6 +341,7 @@ def show():
417
  file_name=f"{project_name}.zip",
418
  mime="application/zip",
419
  use_container_width=True
 
420
  )
421
 
422
  with st.expander("🔗 Endpoints Generados", expanded=True):
@@ -425,345 +350,6 @@ def show():
425
  except Exception as e:
426
  st.error(f"❌ Error generando API: {str(e)}")
427
  st.error("💡 Revisa la configuración y vuelve a intentar")
428
-
429
- # def show():
430
- # st.header("⚡ Generador de API Profesional - E-commerce")
431
-
432
- # # Configuración de API Keys - ACTUALIZADA CON PIXABAY
433
- # with st.expander("🔑 Configuración de APIs Externas", expanded=False):
434
- # # Valores por defecto para ambas APIs
435
- # if 'pixabay_api_key' not in st.session_state:
436
- # st.session_state['pixabay_api_key'] = "52812318-583c94721ffbb74a4f0c5684d"
437
-
438
- # if 'pexels_api_key' not in st.session_state:
439
- # st.session_state['pexels_api_key'] = "jPUxO9Zkb1OzitGkAmI9PeTe3oxqipfsYI3vdfCm0pg8QHFpUeSqVsNS"
440
-
441
- # col1, col2 = st.columns(2)
442
-
443
- # with col1:
444
- # pixabay_api_key = st.text_input(
445
- # "API Key de Pixabay 🥇:",
446
- # value=st.session_state['pixabay_api_key'],
447
- # type="password",
448
- # help="Obtén tu API key gratis en https://pixabay.com/api/docs/"
449
- # )
450
- # st.session_state['pixabay_api_key'] = pixabay_api_key
451
-
452
- # with col2:
453
- # pexels_api_key = st.text_input(
454
- # "API Key de Pexels 🥈:",
455
- # value=st.session_state['pexels_api_key'],
456
- # type="password",
457
- # help="Obtén tu API key gratis en https://www.pexels.com/api/"
458
- # )
459
- # st.session_state['pexels_api_key'] = pexels_api_key
460
-
461
- # # ✅✅✅ CORREGIDO: Inyectar AMBAS API keys ANTES de generar cualquier dato
462
- # from utils.image_generator import configure_image_generator
463
- # configure_image_generator(
464
- # pexels_api_key=st.session_state['pexels_api_key'],
465
- # pixabay_api_key=st.session_state['pixabay_api_key']
466
- # )
467
-
468
- # # ✅ Verificar que las API keys se configuraron correctamente
469
- # from utils.image_generator import image_generator
470
- # apis_configuradas = []
471
-
472
- # if image_generator.pixabay_api_key and image_generator.pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI":
473
- # apis_configuradas.append("🥈 Pixabay") # Cambiado a 🥈
474
-
475
- # if image_generator.pexels_api_key and image_generator.pexels_api_key != "TU_API_KEY_PEXELS_AQUI":
476
- # apis_configuradas.append("🥉 Pexels") # Cambiado a 🥉
477
-
478
- # # ✅ AGREGADO: Verificar Lexica (siempre disponible)
479
- # apis_configuradas.append("🥇 Lexica")
480
-
481
- # if apis_configuradas:
482
- # st.success(f"✅ APIs configuradas: {', '.join(apis_configuradas)}")
483
- # else:
484
- # st.warning("⚠️ No hay APIs configuradas - Se usarán placeholders e IA")
485
-
486
- # # Verificar datos globales
487
- # if st.session_state.get('global_df') is None:
488
- # st.warning("📤 No hay datos cargados en el sistema")
489
- # st.info("💡 Carga un archivo en la barra lateral para generar API desde datos reales, o usa datos mock")
490
-
491
- # st.subheader("🎯 Configuración de la API")
492
-
493
- # # CONFIGURACIÓN PRINCIPAL
494
- # col1, col2 = st.columns(2)
495
-
496
- # with col1:
497
- # api_type = st.radio(
498
- # "Tipo de API:",
499
- # ["🚀 Desde datos cargados", "🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"],
500
- # help="Genera API desde tus datos, con datos de prueba, o combinando ambos"
501
- # )
502
-
503
- # technology = st.selectbox(
504
- # "Tecnología del backend:",
505
- # ["FastAPI (Python - Recomendado)", "Flask (Python)", "Django (Python)", "Spring Boot (Java)", "Express.js (Node.js)"],
506
- # index=0
507
- # )
508
-
509
- # database = st.selectbox(
510
- # "Base de datos:",
511
- # ["SQLite (Desarrollo)", "PostgreSQL (Producción)", "MySQL (Producción)", "MongoDB (NoSQL)"],
512
- # index=0
513
- # )
514
-
515
- # with col2:
516
- # project_name = st.text_input(
517
- # "Nombre del proyecto:",
518
- # value="mi_api_ecommerce",
519
- # help="Nombre de la carpeta y proyecto"
520
- # )
521
-
522
- # api_version = st.text_input(
523
- # "Versión de la API:",
524
- # value="1.0.0",
525
- # help="Versión semántica (ej: 1.0.0)"
526
- # )
527
-
528
- # include_auth = st.checkbox("🔐 Incluir autenticación JWT", value=True)
529
- # include_docs = st.checkbox("📚 Incluir documentación Swagger", value=True)
530
- # include_docker = st.checkbox("🐳 Incluir Docker y Docker Compose", value=True)
531
-
532
- # # CONFIGURACIÓN DE MÓDULOS/ENTIDADES
533
- # st.subheader("🏗️ Módulos de la API E-commerce")
534
-
535
- # modules = []
536
-
537
- # if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
538
- # if st.session_state.get('global_df') is not None:
539
- # df = st.session_state.global_df
540
- # filename = st.session_state.global_filename
541
-
542
- # st.success(f"📊 Datos cargados: {filename}")
543
-
544
- # main_entity = infer_entity_name(filename)
545
-
546
- # with st.expander(f"🔧 Configurar módulo: {main_entity}", expanded=True):
547
- # module_name = st.text_input("Nombre del módulo:", value=main_entity, key="main_module")
548
- # base_route = st.text_input("Ruta base:", value=f"/{main_entity}", key="main_route")
549
-
550
- # st.write("**Configuración de campos:**")
551
- # field_config = {}
552
- # for col in df.columns:
553
- # col1, col2, col3 = st.columns([2, 2, 1])
554
- # with col1:
555
- # field_name = st.text_input("Nombre campo:", value=col, key=f"field_{col}_name")
556
- # with col2:
557
- # field_type = st.selectbox(
558
- # "Tipo:",
559
- # ["string", "integer", "float", "boolean", "datetime", "email", "url"],
560
- # key=f"field_{col}_type"
561
- # )
562
- # with col3:
563
- # required = st.checkbox("Requerido", value=True, key=f"field_{col}_req")
564
-
565
- # field_config[col] = {
566
- # 'name': field_name,
567
- # 'type': field_type,
568
- # 'required': required
569
- # }
570
-
571
- # modules.append({
572
- # 'name': module_name,
573
- # 'route': base_route,
574
- # 'source': 'file',
575
- # 'data': df,
576
- # 'fields': field_config
577
- # })
578
-
579
- # # Agregar módulos adicionales para API Mock
580
- # if api_type in ["🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"]:
581
- # st.write("---")
582
- # st.write("**➕ Agregar módulos mock para E-commerce**")
583
-
584
- # # MÓDULOS ESENCIALES vs OPCIONALES
585
- # essential_modules = ["usuarios", "productos", "categorias", "pedidos", "carrito"]
586
- # optional_modules = ["pagos", "reseñas", "direcciones", "cupones"]
587
-
588
- # col_ess, col_opt = st.columns(2)
589
-
590
- # with col_ess:
591
- # st.write("**🎯 Módulos Esenciales**")
592
- # essential_selected = st.multiselect(
593
- # "Seleccionar módulos esenciales:",
594
- # essential_modules,
595
- # default=essential_modules,
596
- # label_visibility="collapsed"
597
- # )
598
-
599
- # with col_opt:
600
- # st.write("**🔧 Módulos Opcionales**")
601
- # optional_selected = st.multiselect(
602
- # "Seleccionar módulos opcionales:",
603
- # optional_modules,
604
- # default=["pagos", "reseñas"],
605
- # label_visibility="collapsed"
606
- # )
607
-
608
- # mock_modules = essential_selected + optional_selected
609
-
610
- # for module in mock_modules:
611
- # with st.expander(f"🎭 Configurar módulo: {module}", expanded=False):
612
- # module_name = st.text_input("Nombre:", value=module, key=f"mock_{module}_name")
613
- # base_route = st.text_input("Ruta:", value=f"/{module}", key=f"mock_{module}_route")
614
- # record_count = st.slider("Número de registros:", 10, 1000, 50, key=f"mock_{module}_count")
615
-
616
- # # Configuración específica por módulo
617
- # if module in ["productos"]:
618
- # include_images = st.checkbox("🖼️ Incluir imágenes reales", value=True, key=f"mock_{module}_images")
619
- # image_source = st.selectbox(
620
- # "Fuente de imágenes:",
621
- # [
622
- # "🥇 Lexica (Búsquedas específicas con IA)", # PRIMERA
623
- # "🥈 Pollinations AI (Generadas por IA)", # SEGUNDA
624
- # "🥉 Pixabay (Precisas, libres de derechos)", # TERCERA
625
- # "📸 Pexels (Alta calidad)", # CUARTA
626
- # "🪄 Placeholder (Último recurso)",
627
- # "🎯 Orden de prioridad automático"
628
- # ],
629
- # key=f"mock_{module}_imgsrc"
630
- # )
631
-
632
- # categorias_disponibles = [
633
- # 'Electrónica', 'Tecnología', 'Hogar', 'Ropa', 'Deportes',
634
- # 'Juguetes', 'Libros', 'Música', 'Belleza', 'Salud',
635
- # 'Alimentos', 'Bebidas', 'Automotriz', 'Jardín', 'Oficina',
636
- # 'Comidas Dulces', 'Comidas Saladas', 'Bebidas'
637
- # ]
638
-
639
- # categorias_seleccionadas = st.multiselect(
640
- # f"Categorías de {module}:",
641
- # categorias_disponibles,
642
- # default=categorias_disponibles[:5],
643
- # key=f"mock_{module}_cats"
644
- # )
645
-
646
- # if categorias_seleccionadas and any(cat in ['Comidas Dulces', 'Comidas Saladas', 'Bebidas'] for cat in categorias_seleccionadas):
647
- # st.success("🍽️ **Modo Restaurante Activado**: Se generarán productos especializados (tortas, hamburguesas, bebidas, etc.)")
648
- # else:
649
- # include_images = False
650
- # image_source = None
651
- # categorias_seleccionadas = []
652
-
653
- # modules.append({
654
- # 'name': module_name,
655
- # 'route': base_route,
656
- # 'source': 'mock',
657
- # 'type': module,
658
- # 'record_count': record_count,
659
- # 'include_images': include_images,
660
- # 'image_source': image_source,
661
- # 'categorias_seleccionadas': categorias_seleccionadas
662
- # })
663
-
664
- # # CONFIGURACIÓN AVANZADA
665
- # st.subheader("⚙️ Configuración Avanzada")
666
-
667
- # adv_col1, adv_col2 = st.columns(2)
668
-
669
- # with adv_col1:
670
- # cors_enabled = st.checkbox("🌐 Habilitar CORS", value=True)
671
- # rate_limiting = st.checkbox("⏱️ Rate Limiting", value=True)
672
- # file_uploads = st.checkbox("📁 Manejo de archivos", value=True)
673
- # include_migrations = st.checkbox("🔄 Migraciones Alembic", value=True)
674
- # pagination_size = st.slider("Tamaño de paginación:", 10, 100, 25)
675
-
676
- # with adv_col2:
677
- # logging_level = st.selectbox("Nivel de logging:", ["DEBUG", "INFO", "WARNING", "ERROR"])
678
- # include_tests = st.checkbox("🧪 Incluir tests automatizados", value=True)
679
- # generate_sdk = st.checkbox("📦 Generar SDK cliente", value=True)
680
- # populate_db = st.checkbox("🌱 Poblar BD con datos mock", value=True)
681
-
682
- # # GENERACIÓN DE LA API
683
- # st.subheader("🎉 Generar API")
684
-
685
- # if not modules:
686
- # st.warning("Agrega al menos un módulo para generar la API")
687
- # return
688
-
689
- # # Mostrar resumen
690
- # st.write("### 📋 Resumen de la API")
691
- # summary_col1, summary_col2, summary_col3 = st.columns(3)
692
-
693
- # with summary_col1:
694
- # st.metric("Módulos", len(modules))
695
- # st.metric("Tecnología", technology.split(" ")[0])
696
-
697
- # with summary_col2:
698
- # st.metric("Base de datos", database.split(" ")[0])
699
- # st.metric("Autenticación", "Sí" if include_auth else "No")
700
-
701
- # with summary_col3:
702
- # total_records = sum([mod.get('record_count', len(mod.get('data', []))) for mod in modules])
703
- # st.metric("Registros totales", total_records)
704
- # st.metric("Docker", "Sí" if include_docker else "No")
705
-
706
- # # Información del sistema de imágenes - ACTUALIZADA CON LEXICA
707
- # with st.expander("📸 Sistema de Imágenes Configurado", expanded=False):
708
- # st.write("**🎯 Orden de Prioridad:**")
709
- # st.write("1. 🥇 **Lexica** - Búsquedas específicas con AI (Siempre disponible)")
710
- # st.write("2. 🥈 **Pollinations** - Imágenes generadas por IA coherentes")
711
- # st.write("3. 🥉 **Pixabay** - Fotos reales libres de derechos")
712
- # st.write("4. 📸 **Pexels** - Backup con calidad alta")
713
- # st.write("5. 🪄 **Placeholder** - Último recurso (Siempre disponible)")
714
-
715
- # st.info("**💡 Orden automático:** Lexica → Pollinations → Pixabay → Pexels → Placeholder")
716
-
717
- # if apis_configuradas:
718
- # st.success(f"**APIs Configuradas:** {', '.join(apis_configuradas)}")
719
- # else:
720
- # st.info("**Modo automático:** Se usará Lexica + Pollinations + Placeholders")
721
-
722
- # if st.button("⚡ Generar API Completa", type="primary", use_container_width=True):
723
- # with st.spinner("🚀 Generando API profesional para E-commerce..."):
724
- # try:
725
- # api_structure = generate_complete_api(
726
- # project_name=project_name,
727
- # technology=technology,
728
- # database=database,
729
- # modules=modules,
730
- # include_auth=include_auth,
731
- # include_docs=include_docs,
732
- # include_docker=include_docker,
733
- # api_version=api_version,
734
- # cors_enabled=cors_enabled,
735
- # rate_limiting=rate_limiting,
736
- # file_uploads=file_uploads,
737
- # include_migrations=include_migrations,
738
- # pagination_size=pagination_size,
739
- # include_tests=include_tests,
740
- # generate_sdk=generate_sdk,
741
- # logging_level=logging_level,
742
- # populate_db=populate_db
743
- # )
744
-
745
- # zip_buffer = create_api_zip(api_structure, project_name)
746
-
747
- # st.success("✅ API generada exitosamente!")
748
-
749
- # with st.expander("🚀 Instrucciones de Despliegue", expanded=True):
750
- # show_deployment_instructions(technology, database, project_name)
751
-
752
- # st.download_button(
753
- # label="📥 Descargar API Completa",
754
- # data=zip_buffer,
755
- # file_name=f"{project_name}.zip",
756
- # mime="application/zip",
757
- # use_container_width=True
758
- # # ❌ NO usar on_click - ya registramos la métrica al generar
759
- # )
760
-
761
- # with st.expander("🔗 Endpoints Generados", expanded=True):
762
- # show_generated_endpoints(modules)
763
-
764
- # except Exception as e:
765
- # st.error(f"❌ Error generando API: {str(e)}")
766
- # st.error("💡 Revisa la configuración y vuelve a intentar")
767
 
768
  # CONTINUARÁ EN LA SIGUIENTE PARTE...
769
  # CONTINUACIÓN DE api_generator.py
@@ -773,7 +359,7 @@ def infer_entity_name(filename):
773
  name = filename.split('.')[0].lower()
774
 
775
  entity_map = {
776
- # 'clientes': 'usuarios',
777
  'users': 'usuarios',
778
  'products': 'productos',
779
  'items': 'productos',
@@ -1030,7 +616,6 @@ def generate_fastapi_structure(**kwargs):
1030
  "utils/rate_limit.py": generate_rate_limit_utils(**kwargs) if kwargs['rate_limiting'] else "",
1031
  "utils/file_upload.py": generate_file_upload_utils(**kwargs) if kwargs['file_uploads'] else "",
1032
  "utils/image_generator.py": generate_image_generator_utils(**kwargs),
1033
- "utils/backup_manager.py": generate_backup_manager(**kwargs),
1034
 
1035
  # Scripts
1036
  "scripts/__init__.py": "",
@@ -1846,223 +1431,7 @@ def configure_image_generator(pexels_api_key: str = None, pixabay_api_key: str =
1846
  return image_generator
1847
  '''
1848
 
1849
- ####agregada
1850
- def generate_backup_manager(**kwargs):
1851
- """Generar el archivo backup_manager.py para el sistema de respaldos JSON"""
1852
-
1853
- return '''import json
1854
- import os
1855
- from datetime import datetime
1856
- from typing import List, Dict, Any, Optional
1857
- from sqlalchemy.orm import Session
1858
- import logging
1859
-
1860
- class BackupManager:
1861
- """
1862
- Sistema de respaldo automático en JSON para todas las entidades de la base de datos.
1863
- Genera archivos JSON individuales por cada entidad y se actualiza automáticamente.
1864
- """
1865
-
1866
- def __init__(self, backup_dir: str = "backups/json"):
1867
- self.backup_dir = backup_dir
1868
- self.setup_backup_structure()
1869
- self.setup_logging()
1870
- print(f"🔧 BackupManager inicializado - Directorio: {backup_dir}")
1871
-
1872
- def setup_backup_structure(self):
1873
- """Crear estructura de directorios para backups"""
1874
- os.makedirs(self.backup_dir, exist_ok=True)
1875
- os.makedirs(f"{self.backup_dir}/logs", exist_ok=True)
1876
- print(f"📁 Estructura de backups creada: {self.backup_dir}")
1877
-
1878
- def setup_logging(self):
1879
- """Configurar logging para backups"""
1880
- logging.basicConfig(
1881
- filename=f"{self.backup_dir}/logs/backup.log",
1882
- level=logging.INFO,
1883
- format='%(asctime)s - %(levelname)s - %(message)s',
1884
- encoding='utf-8'
1885
- )
1886
- self.logger = logging.getLogger(__name__)
1887
-
1888
- def export_entity_to_json(self, db: Session, model_class, entity_name: str) -> bool:
1889
- """
1890
- Exportar una entidad específica a JSON
1891
-
1892
- Args:
1893
- db: Sesión de base de datos
1894
- model_class: Clase del modelo SQLAlchemy
1895
- entity_name: Nombre de la entidad (para el archivo)
1896
-
1897
- Returns:
1898
- bool: True si fue exitoso, False si hubo error
1899
- """
1900
- try:
1901
- # Obtener todos los registros de la entidad
1902
- records = db.query(model_class).all()
1903
-
1904
- # Convertir registros a diccionario
1905
- data = []
1906
- for record in records:
1907
- record_dict = {}
1908
- for column in record.__table__.columns:
1909
- value = getattr(record, column.name)
1910
-
1911
- # Convertir tipos especiales a formato serializable
1912
- if hasattr(value, 'isoformat'): # datetime, date
1913
- value = value.isoformat()
1914
- elif value is None:
1915
- value = None
1916
- elif isinstance(value, (int, float, str, bool)):
1917
- value = value
1918
- else:
1919
- value = str(value) # Fallback para otros tipos
1920
-
1921
- record_dict[column.name] = value
1922
- data.append(record_dict)
1923
-
1924
- # Estructura del archivo JSON
1925
- backup_data = {
1926
- "metadata": {
1927
- "entity": entity_name,
1928
- "export_date": datetime.now().isoformat(),
1929
- "record_count": len(data),
1930
- "database_timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1931
- },
1932
- "data": data
1933
- }
1934
-
1935
- # Guardar en archio JSON
1936
- backup_file = f"{self.backup_dir}/{entity_name}.json"
1937
- with open(backup_file, 'w', encoding='utf-8') as f:
1938
- json.dump(backup_data, f, indent=2, ensure_ascii=False, default=str)
1939
-
1940
- self.logger.info(f"✅ Backup completado: {entity_name} - {len(data)} registros")
1941
- print(f"💾 Backup actualizado: {entity_name}.json ({len(data)} registros)")
1942
- return True
1943
-
1944
- except Exception as e:
1945
- error_msg = f"❌ Error en backup de {entity_name}: {str(e)}"
1946
- self.logger.error(error_msg)
1947
- print(error_msg)
1948
- return False
1949
-
1950
- def export_all_entities(self, db: Session, models_dict: Dict[str, Any]) -> Dict[str, bool]:
1951
- """
1952
- Exportar todas las entidades a JSON
1953
-
1954
- Args:
1955
- db: Sesión de base de datos
1956
- models_dict: Diccionario con {nombre_entidad: clase_modelo}
1957
-
1958
- Returns:
1959
- Dict: Resultados por entidad {entidad: éxito}
1960
- """
1961
- print("🔄 Iniciando exportación completa de backups...")
1962
- results = {}
1963
-
1964
- for entity_name, model_class in models_dict.items():
1965
- success = self.export_entity_to_json(db, model_class, entity_name)
1966
- results[entity_name] = success
1967
-
1968
- # Estadísticas
1969
- successful = sum(results.values())
1970
- total = len(results)
1971
- print(f"📊 Exportación completada: {successful}/{total} entidades respaldadas")
1972
-
1973
- return results
1974
-
1975
- def get_backup_status(self) -> Dict[str, Any]:
1976
- """
1977
- Obtener estado actual de todos los backups
1978
-
1979
- Returns:
1980
- Dict: Información de todos los archivos de backup
1981
- """
1982
- backups = {}
1983
- total_size_kb = 0
1984
-
1985
- if os.path.exists(self.backup_dir):
1986
- for file in os.listdir(self.backup_dir):
1987
- if file.endswith('.json') and not file.startswith('.'):
1988
- file_path = os.path.join(self.backup_dir, file)
1989
- try:
1990
- file_stats = os.stat(file_path)
1991
- entity_name = file.replace('.json', '')
1992
-
1993
- # Leer metadata del archivo JSON
1994
- metadata = {}
1995
- try:
1996
- with open(file_path, 'r', encoding='utf-8') as f:
1997
- backup_data = json.load(f)
1998
- metadata = backup_data.get('metadata', {})
1999
- except:
2000
- metadata = {"error": "No se pudo leer metadata"}
2001
-
2002
- backups[entity_name] = {
2003
- "file": file,
2004
- "size_kb": round(file_stats.st_size / 1024, 2),
2005
- "modified": datetime.fromtimestamp(file_stats.st_mtime).isoformat(),
2006
- "record_count": metadata.get('record_count', 0),
2007
- "last_export": metadata.get('export_date', 'N/A')
2008
- }
2009
- total_size_kb += file_stats.st_size / 1024
2010
- except Exception as e:
2011
- backups[file] = {"error": str(e)}
2012
-
2013
- return {
2014
- "backups": backups,
2015
- "summary": {
2016
- "total_files": len(backups),
2017
- "total_size_kb": round(total_size_kb, 2),
2018
- "backup_directory": self.backup_dir,
2019
- "timestamp": datetime.now().isoformat()
2020
- }
2021
- }
2022
-
2023
- def backup_after_operation(self, db: Session, model_class, entity_name: str):
2024
- """
2025
- Ejecutar backup después de una operación CRUD
2026
- Versión optimizada para no bloquear la respuesta
2027
- """
2028
- try:
2029
- # Ejecutar en segundo plano (no bloqueante)
2030
- self.export_entity_to_json(db, model_class, entity_name)
2031
- except Exception as e:
2032
- self.logger.error(f"❌ Error en backup automático de {entity_name}: {str(e)}")
2033
-
2034
- def get_entity_backup(self, entity_name: str) -> Optional[Dict]:
2035
- """
2036
- Obtener datos de backup de una entidad específica
2037
-
2038
- Args:
2039
- entity_name: Nombre de la entidad
2040
-
2041
- Returns:
2042
- Dict: Datos del backup o None si no existe
2043
- """
2044
- backup_file = f"{self.backup_dir}/{entity_name}.json"
2045
- if os.path.exists(backup_file):
2046
- try:
2047
- with open(backup_file, 'r', encoding='utf-8') as f:
2048
- return json.load(f)
2049
- except Exception as e:
2050
- self.logger.error(f"❌ Error leyendo backup {entity_name}: {str(e)}")
2051
- return None
2052
- return None
2053
-
2054
- # Instancia global para usar en toda la aplicación
2055
- backup_manager = BackupManager()
2056
 
2057
- # Funciones de conveniencia para importar fácilmente
2058
- def get_backup_manager() -> BackupManager:
2059
- return backup_manager
2060
-
2061
- def configure_backup_manager(backup_dir: str = "backups/json") -> BackupManager:
2062
- global backup_manager
2063
- backup_manager = BackupManager(backup_dir)
2064
- return backup_manager
2065
- '''
2066
 
2067
  # CONTINUARÁ EN LA PARTE 3...
2068
  # PARTE 3: Modelos y Schemas Corregidos
@@ -2569,7 +1938,7 @@ class {schema_name}({schema_name}Base):
2569
  # PARTE 4: Routers y Endpoints Corregidos
2570
 
2571
  def generate_fastapi_router(module, **kwargs):
2572
- """Generar router para un módulo en FastAPI - VERSIÓN CON BACKUPS"""
2573
 
2574
  module_name = module['name']
2575
  class_name = module_name.capitalize()
@@ -2596,7 +1965,6 @@ from sqlalchemy.orm import Session
2596
  from database import get_db
2597
  from models.{module_name} import {class_name}
2598
  from schemas.{module_name} import {schema_name}, {schema_name}Create, {schema_name}Update
2599
- from utils.backup_manager import backup_manager # ✅ NUEVO: Importar backup manager
2600
 
2601
  router = APIRouter()
2602
 
@@ -2632,10 +2000,6 @@ async def create_{module_name.rstrip('s')}(
2632
  db.add(db_{module_name.rstrip('s')})
2633
  db.commit()
2634
  db.refresh(db_{module_name.rstrip('s')})
2635
-
2636
- # ✅ NUEVO: Backup automático después de crear
2637
- backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2638
-
2639
  return db_{module_name.rstrip('s')}
2640
  except Exception as e:
2641
  db.rollback()
@@ -2659,10 +2023,6 @@ async def update_{module_name.rstrip('s')}(
2659
 
2660
  db.commit()
2661
  db.refresh(db_{module_name.rstrip('s')})
2662
-
2663
- # ✅ NUEVO: Backup automático después de actualizar
2664
- backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2665
-
2666
  return db_{module_name.rstrip('s')}
2667
  except Exception as e:
2668
  db.rollback()
@@ -2681,10 +2041,6 @@ async def delete_{module_name.rstrip('s')}(
2681
  try:
2682
  db.delete(db_{module_name.rstrip('s')})
2683
  db.commit()
2684
-
2685
- # ✅ NUEVO: Backup automático después de eliminar
2686
- backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2687
-
2688
  return None
2689
  except Exception as e:
2690
  db.rollback()
@@ -2699,24 +2055,10 @@ async def search_{module_name}(
2699
  ):
2700
  """Buscar {module_name} por término"""
2701
  try:
2702
- # ✅ MEJORADO: Búsqueda más robusta en múltiples campos
2703
- from sqlalchemy import or_
2704
-
2705
- # Determinar campos de búsqueda según el tipo de módulo
2706
- search_fields = []
2707
- if hasattr({class_name}, 'nombre'):
2708
- search_fields.append({class_name}.nombre.ilike(f"%{{q}}%"))
2709
- if hasattr({class_name}, 'descripcion'):
2710
- search_fields.append({class_name}.descripcion.ilike(f"%{{q}}%"))
2711
- if hasattr({class_name}, 'email'):
2712
- search_fields.append({class_name}.email.ilike(f"%{{q}}%"))
2713
-
2714
- if search_fields:
2715
- {module_name} = db.query({class_name}).filter(or_(*search_fields)).offset(skip).limit(limit).all()
2716
- else:
2717
- # Fallback: buscar en todos los campos string
2718
- {module_name} = db.query({class_name}).offset(skip).limit(limit).all()
2719
-
2720
  return {module_name}
2721
  except Exception as e:
2722
  raise HTTPException(status_code=400, detail=f"Error en búsqueda: {{str(e)}}")
@@ -2780,10 +2122,6 @@ async def limpiar_carrito_usuario(usuario_id: int, db: Session = Depends(get_db)
2780
  try:
2781
  db.query({class_name}).filter({class_name}.usuario_id == usuario_id).delete()
2782
  db.commit()
2783
-
2784
- # ✅ NUEVO: Backup automático después de limpiar carrito
2785
- backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2786
-
2787
  return None
2788
  except Exception as e:
2789
  db.rollback()
@@ -2818,10 +2156,6 @@ async def actualizar_estado_pedido(
2818
  pedido.estado = estado
2819
  db.commit()
2820
  db.refresh(pedido)
2821
-
2822
- # ✅ NUEVO: Backup automático después de cambiar estado
2823
- backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2824
-
2825
  return pedido
2826
  '''
2827
 
@@ -2975,7 +2309,7 @@ async def update_me(
2975
 
2976
 
2977
  def generate_fastapi_main(**kwargs):
2978
- """Generar archivo main.py - VERSIÓN CORREGIDA CON PERSISTENCIA Y BACKUPS"""
2979
 
2980
  project_name = kwargs['project_name']
2981
  api_version = kwargs['api_version']
@@ -2988,10 +2322,10 @@ def generate_fastapi_main(**kwargs):
2988
  imports = [
2989
  "from fastapi import FastAPI, Depends, HTTPException, Request",
2990
  "from fastapi.middleware.cors import CORSMiddleware",
2991
- "from fastapi.responses import JSONResponse, FileResponse",
2992
  "from contextlib import asynccontextmanager",
2993
  "import uvicorn",
2994
- "from database import get_db, create_tables, engine", # ✅ CORREGIDO: agregar engine
2995
  "from datetime import datetime",
2996
  "import traceback",
2997
  "import sys",
@@ -3001,9 +2335,6 @@ def generate_fastapi_main(**kwargs):
3001
  # ✅ AGREGAR IMPORT PARA VERIFICAR TABLAS EXISTENTES
3002
  imports.append("from sqlalchemy import inspect")
3003
 
3004
- # ✅ AGREGAR IMPORTS PARA BACKUPS
3005
- imports.append("from fastapi.staticfiles import StaticFiles")
3006
-
3007
  if kwargs['include_auth']:
3008
  imports.append("from routers.auth import router as auth_router")
3009
 
@@ -3087,25 +2418,12 @@ async def lifespan(app: FastAPI):
3087
  print("🛑 Apagando API...")
3088
  print("👋 Hasta pronto!")'''
3089
 
3090
- # ✅ CORREGIDO: Evitar rutas duplicadas con doble "api"
3091
  router_includes = ""
3092
  if kwargs['include_auth']:
3093
  router_includes += 'app.include_router(auth_router, prefix="/api/v1/auth", tags=["auth"])\n'
3094
 
3095
  for module in modules:
3096
- # ✅ CORRECCIÓN: Normalizar rutas para evitar /api/v1/api/usuarios
3097
- route = module["route"]
3098
- # Si la ruta ya empieza con /api/, quitar el /api/ inicial
3099
- if route.startswith("/api/"):
3100
- route = route[4:] # Remover "/api" del inicio
3101
- elif route.startswith("api/"):
3102
- route = route[3:] # Remover "api" del inicio
3103
-
3104
- # Asegurar que la ruta empiece con /
3105
- if not route.startswith("/"):
3106
- route = "/" + route
3107
-
3108
- router_includes += f'app.include_router({module["name"]}_router, prefix="/api/v1{route}", tags=["{module["name"]}"])\n'
3109
 
3110
  return f'''{imports_str}
3111
 
@@ -3113,7 +2431,7 @@ async def lifespan(app: FastAPI):
3113
 
3114
  app = FastAPI(
3115
  title="{project_name.replace('_', ' ').title()}",
3116
- description="API profesional para E-commerce generada automáticamente - CON PERSISTENCIA DE DATOS Y BACKUPS JSON",
3117
  version="{api_version}",
3118
  docs_url="/docs" if {kwargs['include_docs']} else None,
3119
  redoc_url="/redoc" if {kwargs['include_docs']} else None,
@@ -3129,38 +2447,21 @@ app.add_middleware(
3129
  )
3130
 
3131
  {router_includes}
3132
-
3133
- # ✅ SISTEMA DE BACKUPS JSON - Montar directorio estático
3134
- @app.on_event("startup")
3135
- async def startup_backup_system():
3136
- """Inicializar sistema de backups al iniciar la aplicación"""
3137
- backup_dir = "backups/json"
3138
- if not os.path.exists(backup_dir):
3139
- os.makedirs(backup_dir, exist_ok=True)
3140
- print(f"📁 Directorio de backups creado: {{backup_dir}}")
3141
-
3142
- # Montar directorio de backups como estático (SOLO DESARROLLO)
3143
- if os.path.exists(backup_dir):
3144
- app.mount("/backups", StaticFiles(directory=backup_dir), name="backups")
3145
- print("🔗 Backups disponibles en: http://localhost:8000/backups/")
3146
-
3147
  @app.get("/")
3148
  async def root():
3149
  return {{
3150
- "message": "🚀 Bienvenido a {project_name} API - Sistema E-commerce CON PERSISTENCIA Y BACKUPS",
3151
  "version": "{api_version}",
3152
  "status": "operational",
3153
  "timestamp": datetime.utcnow().isoformat(),
3154
  "docs": "/docs" if {kwargs['include_docs']} else None,
3155
- "backups": "/backups" if {kwargs['include_docs']} else None,
3156
  "modules": {module_names},
3157
  "features": {{
3158
  "authentication": {kwargs['include_auth']},
3159
  "documentation": {kwargs['include_docs']},
3160
  "docker": {kwargs['include_docker']},
3161
  "database": "{database}",
3162
- "persistence": True,
3163
- "json_backups": True # ✅ NUEVO: Backups JSON habilitados
3164
  }}
3165
  }}
3166
 
@@ -3177,22 +2478,13 @@ async def health_check():
3177
  except Exception as e:
3178
  db_status = f"error: {{str(e)}}"
3179
 
3180
- # ✅ VERIFICAR SISTEMA DE BACKUPS
3181
- backup_status = "active"
3182
- backup_dir = "backups/json"
3183
- if not os.path.exists(backup_dir):
3184
- backup_status = "directory_not_found"
3185
- elif not os.access(backup_dir, os.W_OK):
3186
- backup_status = "no_write_permission"
3187
-
3188
  return {{
3189
  "status": "healthy",
3190
  "timestamp": datetime.utcnow().isoformat(),
3191
  "service": "{project_name}",
3192
  "version": "{api_version}",
3193
  "database": db_status,
3194
- "backups": backup_status, # ✅ NUEVO: Estado de backups
3195
- "persistence": True
3196
  }}
3197
 
3198
  @app.get("/info")
@@ -3206,89 +2498,32 @@ async def api_info():
3206
  "source": module.get('source', 'unknown')
3207
  }})
3208
 
3209
- # ✅ MEJORADO: Información sobre persistencia y backups
3210
  persistence_info = {{
3211
  "database_persistent": True,
3212
  "data_safe": True,
3213
  "auto_populate": {kwargs['populate_db']},
3214
- "json_backups": True, # ✅ NUEVO
3215
- "backup_directory": "backups/json",
3216
- "warning": "Los datos se mantienen entre reinicios y tienen respaldo JSON"
3217
  }}
3218
 
3219
  return {{
3220
  "name": "{project_name}",
3221
  "version": "{api_version}",
3222
- "description": "API E-commerce generada automáticamente - DATOS PERSISTENTES CON BACKUPS JSON",
3223
  "modules": module_info,
3224
  "database": "{database}",
3225
  "authentication": {kwargs['include_auth']},
3226
  "documentation": {kwargs['include_docs']},
3227
- "backups": True, # ✅ NUEVO
3228
- "persistence": persistence_info,
3229
  "endpoints": {{
3230
  "root": "/",
3231
  "health": "/health",
3232
  "info": "/info",
3233
  "docs": "/docs" if {kwargs['include_docs']} else None,
3234
- "backups": "/backups",
3235
- "api_base": "/api/v1",
3236
- "backup_api": "/api/v1/backups"
3237
  }}
3238
  }}
3239
 
3240
- # ✅ ENDPOINTS DE BACKUP - Agregados después de los endpoints principales
3241
- @app.get("/api/v1/backups/status")
3242
- async def get_backup_status():
3243
- """Obtener estado de los backups JSON"""
3244
- backup_dir = "backups/json"
3245
- backups = {{}}
3246
-
3247
- if os.path.exists(backup_dir):
3248
- for file in os.listdir(backup_dir):
3249
- if file.endswith('.json'):
3250
- file_path = os.path.join(backup_dir, file)
3251
- file_stats = os.stat(file_path)
3252
- backups[file] = {{
3253
- "size_kb": round(file_stats.st_size / 1024, 2),
3254
- "modified": datetime.fromtimestamp(file_stats.st_mtime).isoformat(),
3255
- "entities": file.replace('.json', '')
3256
- }}
3257
-
3258
- return {{
3259
- "status": "success",
3260
- "backups": backups,
3261
- "backup_count": len(backups),
3262
- "timestamp": datetime.utcnow().isoformat(),
3263
- "backup_directory": backup_dir
3264
- }}
3265
-
3266
- @app.get("/api/v1/backups/download/{{entity_name}}")
3267
- async def download_backup(entity_name: str):
3268
- """Descargar backup específico de una entidad"""
3269
- backup_file = f"backups/json/{{entity_name}}.json"
3270
- if os.path.exists(backup_file):
3271
- return FileResponse(
3272
- backup_file,
3273
- media_type='application/json',
3274
- filename=f"{{entity_name}}_backup.json"
3275
- )
3276
- raise HTTPException(status_code=404, detail=f"Backup no encontrado para entidad: {{entity_name}}")
3277
-
3278
- @app.get("/backups")
3279
- async def backups_info():
3280
- """Página de información de backups (para navegador)"""
3281
- return {{
3282
- "message": "Sistema de Backups JSON",
3283
- "description": "Backups automáticos de todas las entidades de la base de datos",
3284
- "endpoints": {{
3285
- "view_backups": "http://localhost:8000/backups/ (en navegador)",
3286
- "api_status": "GET /api/v1/backups/status",
3287
- "download": "GET /api/v1/backups/download/{{entity_name}}"
3288
- }},
3289
- "note": "Los backups se generan automáticamente después de cada operación CRUD"
3290
- }}
3291
-
3292
  @app.exception_handler(500)
3293
  async def internal_server_error_handler(request: Request, exc: Exception):
3294
  return JSONResponse(
@@ -3327,10 +2562,8 @@ async def validation_exception_handler(request: Request, exc: Exception):
3327
  if __name__ == "__main__":
3328
  print("🎪 Iniciando servidor de desarrollo...")
3329
  print("📖 Documentación disponible en: http://localhost:8000/docs")
3330
- print("💾 Backups JSON disponibles en: http://localhost:8000/backups/")
3331
  print("🔧 Modo: Desarrollo (Auto-reload activado)")
3332
  print("💾 MODO PERSISTENTE: Los datos se mantienen entre reinicios")
3333
- print("📁 BACKUPS ACTIVOS: Respaldos JSON automáticos")
3334
 
3335
  uvicorn.run(
3336
  "main:app",
@@ -3766,7 +2999,7 @@ default_users_data = get_default_users()
3766
  return mock_data_code
3767
 
3768
  def generate_populate_script(**kwargs):
3769
- """Generar script para poblar la base de datos - VERSIÓN CON BACKUPS AUTOMÁTICOS"""
3770
 
3771
  mock_modules = [m for m in kwargs['modules'] if m['source'] == 'mock' and kwargs['populate_db']]
3772
 
@@ -3920,18 +3153,6 @@ configure_image_generator(
3920
  print(f" ✅ {module_name} poblados exitosamente: {{added_count}} registros agregados")
3921
  if error_count > 0:
3922
  print(f" ⚠️ Se omitieron {{error_count}} registros debido a errores")
3923
-
3924
- # ✅ NUEVO: GENERAR BACKUP DESPUÉS DE POBLAR CADA MÓDULO
3925
- try:
3926
- from utils.backup_manager import backup_manager
3927
- backup_success = backup_manager.export_entity_to_json(db, model_class, "{module_name}")
3928
- if backup_success:
3929
- print(f" 💾 Backup JSON generado: {module_name}.json")
3930
- else:
3931
- print(f" ⚠️ Error generando backup de {module_name}")
3932
- except Exception as backup_error:
3933
- print(f" ⚠️ Error en sistema de backup: {{backup_error}}")
3934
-
3935
  except Exception as e:
3936
  db.rollback()
3937
  print(f" ❌ Error en inserción masiva de {module_name}: {{str(e)}}")
@@ -3957,7 +3178,7 @@ configure_image_generator(
3957
  module_names = [m['name'] for m in mock_modules]
3958
 
3959
  return f'''#!/usr/bin/env python3
3960
- \"\"\"Script para poblar la base de datos con datos iniciales - VERSIÓN CON BACKUPS AUTOMÁTICOS\"\"\"
3961
 
3962
  import sys
3963
  import os
@@ -3973,11 +3194,10 @@ import models
3973
  {imports_str}
3974
 
3975
  def populate_initial_data():
3976
- \"\"\"Poblar la base de datos con datos iniciales - CON BACKUPS JSON AUTOMÁTICOS\"\"\"
3977
  print("🚀 Iniciando población de base de datos...")
3978
  print("💡 NOTA: Todos los IDs serán generados automáticamente por la base de datos")
3979
  print("✅ TODOS los campos financieros y fechas se preservarán (subtotal, iva, descuento, total, fechas)")
3980
- print("💾 BACKUPS: Se generarán archivos JSON automáticamente para cada entidad")
3981
 
3982
  print("🗄️ Creando tablas...")
3983
  try:
@@ -3993,40 +3213,8 @@ def populate_initial_data():
3993
 
3994
  print("\\n🎉 Proceso de población completado!")
3995
 
3996
- # ✅ NUEVO: GENERAR BACKUP COMPLETO DESPUÉS DE POBLAR TODOS LOS MÓDULOS
3997
- print("\\n💾 Generando backups JSON completos...")
3998
- try:
3999
- from utils.backup_manager import backup_manager
4000
-
4001
- # Crear diccionario de modelos para backup
4002
- models_dict = {{}}
4003
- for module_name in {module_names}:
4004
- try:
4005
- model_class = getattr(models, module_name.capitalize())
4006
- models_dict[module_name] = model_class
4007
- except AttributeError:
4008
- print(f" ⚠️ No se pudo encontrar modelo para: {{module_name}}")
4009
-
4010
- if models_dict:
4011
- backup_results = backup_manager.export_all_entities(db, models_dict)
4012
- successful_backups = sum(backup_results.values())
4013
- total_backups = len(backup_results)
4014
- print(f" 📊 Backups generados: {{successful_backups}}/{{total_backups}} entidades")
4015
-
4016
- # Mostrar resumen de backups
4017
- backup_status = backup_manager.get_backup_status()
4018
- print(f" 📁 Directorio de backups: {{backup_status['summary']['backup_directory']}}")
4019
- print(f" 💽 Tamaño total: {{backup_status['summary']['total_size_kb']}} KB")
4020
- else:
4021
- print(" ⚠️ No se pudieron generar backups - sin modelos encontrados")
4022
-
4023
- except Exception as backup_error:
4024
- print(f" ❌ Error en sistema de backups: {{backup_error}}")
4025
- import traceback
4026
- traceback.print_exc()
4027
-
4028
  print("\\n📊 RESUMEN FINAL:")
4029
- print("=" * 60)
4030
 
4031
  total_records = 0
4032
  for module_name in {module_names}:
@@ -4040,10 +3228,8 @@ def populate_initial_data():
4040
  except Exception as e:
4041
  print(f" ❌ {{module_name.capitalize():.<15}} Error: {{e}}")
4042
 
4043
- print("=" * 60)
4044
- print(f" 📈 TOTAL REGISTROS: {{total_records:>18}}")
4045
- print(f" 💾 BACKUPS JSON: {'✅ ACTIVOS':>24}")
4046
- print(f" 📁 DIRECTORIO: {'backups/json/':>24}")
4047
 
4048
  # ✅ VERIFICACIÓN DE CAMPOS FINANCIEROS EN MÓDULOS CLAVE
4049
  print("\\n💰 VERIFICACIÓN DE CAMPOS FINANCIEROS:")
@@ -4087,12 +3273,6 @@ def populate_initial_data():
4087
  except Exception as e:
4088
  print(f" ℹ️ No se pudieron verificar usuarios del sistema: {{e}}")
4089
 
4090
- # ✅ NUEVO: INFORMACIÓN SOBRE BACKUPS
4091
- print("\\n🔗 ACCESO A BACKUPS:")
4092
- print(" 🌐 Ver en navegador: http://localhost:8000/backups/")
4093
- print(" 📊 Estado de backups: http://localhost:8000/api/v1/backups/status")
4094
- print(" 💾 Descargar backups: http://localhost:8000/api/v1/backups/download/{{entidad}}")
4095
-
4096
  except Exception as e:
4097
  print(f"💥 Error general en población: {{str(e)}}")
4098
  db.rollback()
@@ -6407,4 +5587,5 @@ Si encuentras algún problema o tienes preguntas:
6407
 
6408
  # Reemplazar la función generate_readme original
6409
  def generate_readme(**kwargs):
6410
- return generate_complete_readme(**kwargs)
 
 
12
  from typing import Dict, List, Any
13
  import re
14
 
 
15
  def show():
16
  st.header("⚡ Generador de API Profesional - E-commerce")
17
 
 
120
 
121
  modules = []
122
 
 
123
  if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
124
  if st.session_state.get('global_df') is not None:
125
  df = st.session_state.global_df
 
161
  'data': df,
162
  'fields': field_config
163
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
 
165
  # Agregar módulos adicionales para API Mock
166
  if api_type in ["🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"]:
 
197
  with st.expander(f"🎭 Configurar módulo: {module}", expanded=False):
198
  module_name = st.text_input("Nombre:", value=module, key=f"mock_{module}_name")
199
  base_route = st.text_input("Ruta:", value=f"/{module}", key=f"mock_{module}_route")
200
+ record_count = st.slider("Número de registros:", 10, 1000, 50, key=f"mock_{module}_count")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
  # Configuración específica por módulo
203
  if module in ["productos"]:
 
236
  image_source = None
237
  categorias_seleccionadas = []
238
 
239
+ modules.append({
 
240
  'name': module_name,
241
  'route': base_route,
242
  'source': 'mock',
 
245
  'include_images': include_images,
246
  'image_source': image_source,
247
  'categorias_seleccionadas': categorias_seleccionadas
248
+ })
249
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  # CONFIGURACIÓN AVANZADA
251
  st.subheader("⚙️ Configuración Avanzada")
252
 
 
257
  rate_limiting = st.checkbox("⏱️ Rate Limiting", value=True)
258
  file_uploads = st.checkbox("📁 Manejo de archivos", value=True)
259
  include_migrations = st.checkbox("🔄 Migraciones Alembic", value=True)
260
+ pagination_size = st.slider("Tamaño de paginación:", 10, 100, 25)
261
 
262
  with adv_col2:
263
  logging_level = st.selectbox("Nivel de logging:", ["DEBUG", "INFO", "WARNING", "ERROR"])
 
341
  file_name=f"{project_name}.zip",
342
  mime="application/zip",
343
  use_container_width=True
344
+ # ❌ NO usar on_click - ya registramos la métrica al generar
345
  )
346
 
347
  with st.expander("🔗 Endpoints Generados", expanded=True):
 
350
  except Exception as e:
351
  st.error(f"❌ Error generando API: {str(e)}")
352
  st.error("💡 Revisa la configuración y vuelve a intentar")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
  # CONTINUARÁ EN LA SIGUIENTE PARTE...
355
  # CONTINUACIÓN DE api_generator.py
 
359
  name = filename.split('.')[0].lower()
360
 
361
  entity_map = {
362
+ 'clientes': 'usuarios',
363
  'users': 'usuarios',
364
  'products': 'productos',
365
  'items': 'productos',
 
616
  "utils/rate_limit.py": generate_rate_limit_utils(**kwargs) if kwargs['rate_limiting'] else "",
617
  "utils/file_upload.py": generate_file_upload_utils(**kwargs) if kwargs['file_uploads'] else "",
618
  "utils/image_generator.py": generate_image_generator_utils(**kwargs),
 
619
 
620
  # Scripts
621
  "scripts/__init__.py": "",
 
1431
  return image_generator
1432
  '''
1433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1434
 
 
 
 
 
 
 
 
 
 
1435
 
1436
  # CONTINUARÁ EN LA PARTE 3...
1437
  # PARTE 3: Modelos y Schemas Corregidos
 
1938
  # PARTE 4: Routers y Endpoints Corregidos
1939
 
1940
  def generate_fastapi_router(module, **kwargs):
1941
+ """Generar router para un módulo en FastAPI - VERSIÓN CORREGIDA"""
1942
 
1943
  module_name = module['name']
1944
  class_name = module_name.capitalize()
 
1965
  from database import get_db
1966
  from models.{module_name} import {class_name}
1967
  from schemas.{module_name} import {schema_name}, {schema_name}Create, {schema_name}Update
 
1968
 
1969
  router = APIRouter()
1970
 
 
2000
  db.add(db_{module_name.rstrip('s')})
2001
  db.commit()
2002
  db.refresh(db_{module_name.rstrip('s')})
 
 
 
 
2003
  return db_{module_name.rstrip('s')}
2004
  except Exception as e:
2005
  db.rollback()
 
2023
 
2024
  db.commit()
2025
  db.refresh(db_{module_name.rstrip('s')})
 
 
 
 
2026
  return db_{module_name.rstrip('s')}
2027
  except Exception as e:
2028
  db.rollback()
 
2041
  try:
2042
  db.delete(db_{module_name.rstrip('s')})
2043
  db.commit()
 
 
 
 
2044
  return None
2045
  except Exception as e:
2046
  db.rollback()
 
2055
  ):
2056
  """Buscar {module_name} por término"""
2057
  try:
2058
+ # Búsqueda en campos comunes
2059
+ {module_name} = db.query({class_name}).filter(
2060
+ {class_name}.nombre.ilike(f"%{{q}}%")
2061
+ ).offset(skip).limit(limit).all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2062
  return {module_name}
2063
  except Exception as e:
2064
  raise HTTPException(status_code=400, detail=f"Error en búsqueda: {{str(e)}}")
 
2122
  try:
2123
  db.query({class_name}).filter({class_name}.usuario_id == usuario_id).delete()
2124
  db.commit()
 
 
 
 
2125
  return None
2126
  except Exception as e:
2127
  db.rollback()
 
2156
  pedido.estado = estado
2157
  db.commit()
2158
  db.refresh(pedido)
 
 
 
 
2159
  return pedido
2160
  '''
2161
 
 
2309
 
2310
 
2311
  def generate_fastapi_main(**kwargs):
2312
+ """Generar archivo main.py - VERSIÓN CORREGIDA CON PERSISTENCIA"""
2313
 
2314
  project_name = kwargs['project_name']
2315
  api_version = kwargs['api_version']
 
2322
  imports = [
2323
  "from fastapi import FastAPI, Depends, HTTPException, Request",
2324
  "from fastapi.middleware.cors import CORSMiddleware",
2325
+ "from fastapi.responses import JSONResponse",
2326
  "from contextlib import asynccontextmanager",
2327
  "import uvicorn",
2328
+ "from database import engine, create_tables",
2329
  "from datetime import datetime",
2330
  "import traceback",
2331
  "import sys",
 
2335
  # ✅ AGREGAR IMPORT PARA VERIFICAR TABLAS EXISTENTES
2336
  imports.append("from sqlalchemy import inspect")
2337
 
 
 
 
2338
  if kwargs['include_auth']:
2339
  imports.append("from routers.auth import router as auth_router")
2340
 
 
2418
  print("🛑 Apagando API...")
2419
  print("👋 Hasta pronto!")'''
2420
 
 
2421
  router_includes = ""
2422
  if kwargs['include_auth']:
2423
  router_includes += 'app.include_router(auth_router, prefix="/api/v1/auth", tags=["auth"])\n'
2424
 
2425
  for module in modules:
2426
+ router_includes += f'app.include_router({module["name"]}_router, prefix="/api/v1{module["route"]}", tags=["{module["name"]}"])\n'
 
 
 
 
 
 
 
 
 
 
 
 
2427
 
2428
  return f'''{imports_str}
2429
 
 
2431
 
2432
  app = FastAPI(
2433
  title="{project_name.replace('_', ' ').title()}",
2434
+ description="API profesional para E-commerce generada automáticamente - CON PERSISTENCIA DE DATOS",
2435
  version="{api_version}",
2436
  docs_url="/docs" if {kwargs['include_docs']} else None,
2437
  redoc_url="/redoc" if {kwargs['include_docs']} else None,
 
2447
  )
2448
 
2449
  {router_includes}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2450
  @app.get("/")
2451
  async def root():
2452
  return {{
2453
+ "message": "🚀 Bienvenido a {project_name} API - Sistema E-commerce CON PERSISTENCIA",
2454
  "version": "{api_version}",
2455
  "status": "operational",
2456
  "timestamp": datetime.utcnow().isoformat(),
2457
  "docs": "/docs" if {kwargs['include_docs']} else None,
 
2458
  "modules": {module_names},
2459
  "features": {{
2460
  "authentication": {kwargs['include_auth']},
2461
  "documentation": {kwargs['include_docs']},
2462
  "docker": {kwargs['include_docker']},
2463
  "database": "{database}",
2464
+ "persistence": True # ✅ NUEVO: Indicar que tiene persistencia
 
2465
  }}
2466
  }}
2467
 
 
2478
  except Exception as e:
2479
  db_status = f"error: {{str(e)}}"
2480
 
 
 
 
 
 
 
 
 
2481
  return {{
2482
  "status": "healthy",
2483
  "timestamp": datetime.utcnow().isoformat(),
2484
  "service": "{project_name}",
2485
  "version": "{api_version}",
2486
  "database": db_status,
2487
+ "persistence": True # ✅ NUEVO
 
2488
  }}
2489
 
2490
  @app.get("/info")
 
2498
  "source": module.get('source', 'unknown')
2499
  }})
2500
 
2501
+ # ✅ MEJORADO: Información sobre persistencia
2502
  persistence_info = {{
2503
  "database_persistent": True,
2504
  "data_safe": True,
2505
  "auto_populate": {kwargs['populate_db']},
2506
+ "warning": "Los datos se mantienen entre reinicios"
 
 
2507
  }}
2508
 
2509
  return {{
2510
  "name": "{project_name}",
2511
  "version": "{api_version}",
2512
+ "description": "API E-commerce generada automáticamente - DATOS PERSISTENTES",
2513
  "modules": module_info,
2514
  "database": "{database}",
2515
  "authentication": {kwargs['include_auth']},
2516
  "documentation": {kwargs['include_docs']},
2517
+ "persistence": persistence_info, # ✅ NUEVO
 
2518
  "endpoints": {{
2519
  "root": "/",
2520
  "health": "/health",
2521
  "info": "/info",
2522
  "docs": "/docs" if {kwargs['include_docs']} else None,
2523
+ "api_base": "/api/v1"
 
 
2524
  }}
2525
  }}
2526
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2527
  @app.exception_handler(500)
2528
  async def internal_server_error_handler(request: Request, exc: Exception):
2529
  return JSONResponse(
 
2562
  if __name__ == "__main__":
2563
  print("🎪 Iniciando servidor de desarrollo...")
2564
  print("📖 Documentación disponible en: http://localhost:8000/docs")
 
2565
  print("🔧 Modo: Desarrollo (Auto-reload activado)")
2566
  print("💾 MODO PERSISTENTE: Los datos se mantienen entre reinicios")
 
2567
 
2568
  uvicorn.run(
2569
  "main:app",
 
2999
  return mock_data_code
3000
 
3001
  def generate_populate_script(**kwargs):
3002
+ """Generar script para poblar la base de datos - VERSIÓN CORREGIDA SIN ELIMINAR CAMPOS ESENCIALES"""
3003
 
3004
  mock_modules = [m for m in kwargs['modules'] if m['source'] == 'mock' and kwargs['populate_db']]
3005
 
 
3153
  print(f" ✅ {module_name} poblados exitosamente: {{added_count}} registros agregados")
3154
  if error_count > 0:
3155
  print(f" ⚠️ Se omitieron {{error_count}} registros debido a errores")
 
 
 
 
 
 
 
 
 
 
 
 
3156
  except Exception as e:
3157
  db.rollback()
3158
  print(f" ❌ Error en inserción masiva de {module_name}: {{str(e)}}")
 
3178
  module_names = [m['name'] for m in mock_modules]
3179
 
3180
  return f'''#!/usr/bin/env python3
3181
+ \"\"\"Script para poblar la base de datos con datos iniciales - VERSIÓN CORREGIDA SIN ELIMINAR CAMPOS ESENCIALES\"\"\"
3182
 
3183
  import sys
3184
  import os
 
3194
  {imports_str}
3195
 
3196
  def populate_initial_data():
3197
+ \"\"\"Poblar la base de datos con datos iniciales - IDs generados automáticamente por la BD\"\"\"
3198
  print("🚀 Iniciando población de base de datos...")
3199
  print("💡 NOTA: Todos los IDs serán generados automáticamente por la base de datos")
3200
  print("✅ TODOS los campos financieros y fechas se preservarán (subtotal, iva, descuento, total, fechas)")
 
3201
 
3202
  print("🗄️ Creando tablas...")
3203
  try:
 
3213
 
3214
  print("\\n🎉 Proceso de población completado!")
3215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3216
  print("\\n📊 RESUMEN FINAL:")
3217
+ print("=" * 50)
3218
 
3219
  total_records = 0
3220
  for module_name in {module_names}:
 
3228
  except Exception as e:
3229
  print(f" ❌ {{module_name.capitalize():.<15}} Error: {{e}}")
3230
 
3231
+ print("=" * 50)
3232
+ print(f" 📈 TOTAL: {{total_records:>23}} registros")
 
 
3233
 
3234
  # ✅ VERIFICACIÓN DE CAMPOS FINANCIEROS EN MÓDULOS CLAVE
3235
  print("\\n💰 VERIFICACIÓN DE CAMPOS FINANCIEROS:")
 
3273
  except Exception as e:
3274
  print(f" ℹ️ No se pudieron verificar usuarios del sistema: {{e}}")
3275
 
 
 
 
 
 
 
3276
  except Exception as e:
3277
  print(f"💥 Error general en población: {{str(e)}}")
3278
  db.rollback()
 
5587
 
5588
  # Reemplazar la función generate_readme original
5589
  def generate_readme(**kwargs):
5590
+ return generate_complete_readme(**kwargs)
5591
+
requirements.txt CHANGED
Binary files a/requirements.txt and b/requirements.txt differ