DePol1 commited on
Commit
62556eb
·
verified ·
1 Parent(s): 26ea481
Files changed (1) hide show
  1. frontend/web/modules/api_generator.py +789 -27
frontend/web/modules/api_generator.py CHANGED
@@ -121,6 +121,24 @@ def show():
121
 
122
  modules = []
123
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
125
  if st.session_state.get('global_df') is not None:
126
  df = st.session_state.global_df
@@ -282,6 +300,7 @@ def show():
282
  st.metric("Tecnología", technology.split(" ")[0])
283
 
284
  with summary_col2:
 
285
  st.metric("Base de datos", database.split(" ")[0])
286
  st.metric("Autenticación", "Sí" if include_auth else "No")
287
 
@@ -342,7 +361,6 @@ def show():
342
  file_name=f"{project_name}.zip",
343
  mime="application/zip",
344
  use_container_width=True
345
- # ❌ NO usar on_click - ya registramos la métrica al generar
346
  )
347
 
348
  with st.expander("🔗 Endpoints Generados", expanded=True):
@@ -351,6 +369,345 @@ def show():
351
  except Exception as e:
352
  st.error(f"❌ Error generando API: {str(e)}")
353
  st.error("💡 Revisa la configuración y vuelve a intentar")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
  # CONTINUARÁ EN LA SIGUIENTE PARTE...
356
  # CONTINUACIÓN DE api_generator.py
@@ -617,6 +974,7 @@ def generate_fastapi_structure(**kwargs):
617
  "utils/rate_limit.py": generate_rate_limit_utils(**kwargs) if kwargs['rate_limiting'] else "",
618
  "utils/file_upload.py": generate_file_upload_utils(**kwargs) if kwargs['file_uploads'] else "",
619
  "utils/image_generator.py": generate_image_generator_utils(**kwargs),
 
620
 
621
  # Scripts
622
  "scripts/__init__.py": "",
@@ -1432,7 +1790,223 @@ def configure_image_generator(pexels_api_key: str = None, pixabay_api_key: str =
1432
  return image_generator
1433
  '''
1434
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1435
 
 
 
 
 
 
 
 
 
 
 
 
 
1436
 
1437
  # CONTINUARÁ EN LA PARTE 3...
1438
  # PARTE 3: Modelos y Schemas Corregidos
@@ -1939,7 +2513,7 @@ class {schema_name}({schema_name}Base):
1939
  # PARTE 4: Routers y Endpoints Corregidos
1940
 
1941
  def generate_fastapi_router(module, **kwargs):
1942
- """Generar router para un módulo en FastAPI - VERSIÓN CORREGIDA"""
1943
 
1944
  module_name = module['name']
1945
  class_name = module_name.capitalize()
@@ -1966,6 +2540,7 @@ from sqlalchemy.orm import Session
1966
  from database import get_db
1967
  from models.{module_name} import {class_name}
1968
  from schemas.{module_name} import {schema_name}, {schema_name}Create, {schema_name}Update
 
1969
 
1970
  router = APIRouter()
1971
 
@@ -2001,6 +2576,10 @@ async def create_{module_name.rstrip('s')}(
2001
  db.add(db_{module_name.rstrip('s')})
2002
  db.commit()
2003
  db.refresh(db_{module_name.rstrip('s')})
 
 
 
 
2004
  return db_{module_name.rstrip('s')}
2005
  except Exception as e:
2006
  db.rollback()
@@ -2024,6 +2603,10 @@ async def update_{module_name.rstrip('s')}(
2024
 
2025
  db.commit()
2026
  db.refresh(db_{module_name.rstrip('s')})
 
 
 
 
2027
  return db_{module_name.rstrip('s')}
2028
  except Exception as e:
2029
  db.rollback()
@@ -2042,6 +2625,10 @@ async def delete_{module_name.rstrip('s')}(
2042
  try:
2043
  db.delete(db_{module_name.rstrip('s')})
2044
  db.commit()
 
 
 
 
2045
  return None
2046
  except Exception as e:
2047
  db.rollback()
@@ -2056,10 +2643,24 @@ async def search_{module_name}(
2056
  ):
2057
  """Buscar {module_name} por término"""
2058
  try:
2059
- # Búsqueda en campos comunes
2060
- {module_name} = db.query({class_name}).filter(
2061
- {class_name}.nombre.ilike(f"%{{q}}%")
2062
- ).offset(skip).limit(limit).all()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2063
  return {module_name}
2064
  except Exception as e:
2065
  raise HTTPException(status_code=400, detail=f"Error en búsqueda: {{str(e)}}")
@@ -2123,6 +2724,10 @@ async def limpiar_carrito_usuario(usuario_id: int, db: Session = Depends(get_db)
2123
  try:
2124
  db.query({class_name}).filter({class_name}.usuario_id == usuario_id).delete()
2125
  db.commit()
 
 
 
 
2126
  return None
2127
  except Exception as e:
2128
  db.rollback()
@@ -2157,6 +2762,10 @@ async def actualizar_estado_pedido(
2157
  pedido.estado = estado
2158
  db.commit()
2159
  db.refresh(pedido)
 
 
 
 
2160
  return pedido
2161
  '''
2162
 
@@ -2310,7 +2919,7 @@ async def update_me(
2310
 
2311
 
2312
  def generate_fastapi_main(**kwargs):
2313
- """Generar archivo main.py - VERSIÓN CORREGIDA CON PERSISTENCIA"""
2314
 
2315
  project_name = kwargs['project_name']
2316
  api_version = kwargs['api_version']
@@ -2323,10 +2932,10 @@ def generate_fastapi_main(**kwargs):
2323
  imports = [
2324
  "from fastapi import FastAPI, Depends, HTTPException, Request",
2325
  "from fastapi.middleware.cors import CORSMiddleware",
2326
- "from fastapi.responses import JSONResponse",
2327
  "from contextlib import asynccontextmanager",
2328
  "import uvicorn",
2329
- "from database import engine, create_tables",
2330
  "from datetime import datetime",
2331
  "import traceback",
2332
  "import sys",
@@ -2336,6 +2945,9 @@ def generate_fastapi_main(**kwargs):
2336
  # ✅ AGREGAR IMPORT PARA VERIFICAR TABLAS EXISTENTES
2337
  imports.append("from sqlalchemy import inspect")
2338
 
 
 
 
2339
  if kwargs['include_auth']:
2340
  imports.append("from routers.auth import router as auth_router")
2341
 
@@ -2419,12 +3031,25 @@ async def lifespan(app: FastAPI):
2419
  print("🛑 Apagando API...")
2420
  print("👋 Hasta pronto!")'''
2421
 
 
2422
  router_includes = ""
2423
  if kwargs['include_auth']:
2424
  router_includes += 'app.include_router(auth_router, prefix="/api/v1/auth", tags=["auth"])\n'
2425
 
2426
  for module in modules:
2427
- router_includes += f'app.include_router({module["name"]}_router, prefix="/api/v1{module["route"]}", tags=["{module["name"]}"])\n'
 
 
 
 
 
 
 
 
 
 
 
 
2428
 
2429
  return f'''{imports_str}
2430
 
@@ -2432,7 +3057,7 @@ async def lifespan(app: FastAPI):
2432
 
2433
  app = FastAPI(
2434
  title="{project_name.replace('_', ' ').title()}",
2435
- description="API profesional para E-commerce generada automáticamente - CON PERSISTENCIA DE DATOS",
2436
  version="{api_version}",
2437
  docs_url="/docs" if {kwargs['include_docs']} else None,
2438
  redoc_url="/redoc" if {kwargs['include_docs']} else None,
@@ -2448,21 +3073,38 @@ app.add_middleware(
2448
  )
2449
 
2450
  {router_includes}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2451
  @app.get("/")
2452
  async def root():
2453
  return {{
2454
- "message": "🚀 Bienvenido a {project_name} API - Sistema E-commerce CON PERSISTENCIA",
2455
  "version": "{api_version}",
2456
  "status": "operational",
2457
  "timestamp": datetime.utcnow().isoformat(),
2458
  "docs": "/docs" if {kwargs['include_docs']} else None,
 
2459
  "modules": {module_names},
2460
  "features": {{
2461
  "authentication": {kwargs['include_auth']},
2462
  "documentation": {kwargs['include_docs']},
2463
  "docker": {kwargs['include_docker']},
2464
  "database": "{database}",
2465
- "persistence": True # ✅ NUEVO: Indicar que tiene persistencia
 
2466
  }}
2467
  }}
2468
 
@@ -2479,13 +3121,22 @@ async def health_check():
2479
  except Exception as e:
2480
  db_status = f"error: {{str(e)}}"
2481
 
 
 
 
 
 
 
 
 
2482
  return {{
2483
  "status": "healthy",
2484
  "timestamp": datetime.utcnow().isoformat(),
2485
  "service": "{project_name}",
2486
  "version": "{api_version}",
2487
  "database": db_status,
2488
- "persistence": True # ✅ NUEVO
 
2489
  }}
2490
 
2491
  @app.get("/info")
@@ -2499,32 +3150,89 @@ async def api_info():
2499
  "source": module.get('source', 'unknown')
2500
  }})
2501
 
2502
- # ✅ MEJORADO: Información sobre persistencia
2503
  persistence_info = {{
2504
  "database_persistent": True,
2505
  "data_safe": True,
2506
  "auto_populate": {kwargs['populate_db']},
2507
- "warning": "Los datos se mantienen entre reinicios"
 
 
2508
  }}
2509
 
2510
  return {{
2511
  "name": "{project_name}",
2512
  "version": "{api_version}",
2513
- "description": "API E-commerce generada automáticamente - DATOS PERSISTENTES",
2514
  "modules": module_info,
2515
  "database": "{database}",
2516
  "authentication": {kwargs['include_auth']},
2517
  "documentation": {kwargs['include_docs']},
2518
- "persistence": persistence_info, # ✅ NUEVO
 
2519
  "endpoints": {{
2520
  "root": "/",
2521
  "health": "/health",
2522
  "info": "/info",
2523
  "docs": "/docs" if {kwargs['include_docs']} else None,
2524
- "api_base": "/api/v1"
 
 
2525
  }}
2526
  }}
2527
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2528
  @app.exception_handler(500)
2529
  async def internal_server_error_handler(request: Request, exc: Exception):
2530
  return JSONResponse(
@@ -2563,8 +3271,10 @@ async def validation_exception_handler(request: Request, exc: Exception):
2563
  if __name__ == "__main__":
2564
  print("🎪 Iniciando servidor de desarrollo...")
2565
  print("📖 Documentación disponible en: http://localhost:8000/docs")
 
2566
  print("🔧 Modo: Desarrollo (Auto-reload activado)")
2567
  print("💾 MODO PERSISTENTE: Los datos se mantienen entre reinicios")
 
2568
 
2569
  uvicorn.run(
2570
  "main:app",
@@ -3000,7 +3710,7 @@ default_users_data = get_default_users()
3000
  return mock_data_code
3001
 
3002
  def generate_populate_script(**kwargs):
3003
- """Generar script para poblar la base de datos - VERSIÓN CORREGIDA SIN ELIMINAR CAMPOS ESENCIALES"""
3004
 
3005
  mock_modules = [m for m in kwargs['modules'] if m['source'] == 'mock' and kwargs['populate_db']]
3006
 
@@ -3154,6 +3864,18 @@ configure_image_generator(
3154
  print(f" ✅ {module_name} poblados exitosamente: {{added_count}} registros agregados")
3155
  if error_count > 0:
3156
  print(f" ⚠️ Se omitieron {{error_count}} registros debido a errores")
 
 
 
 
 
 
 
 
 
 
 
 
3157
  except Exception as e:
3158
  db.rollback()
3159
  print(f" ❌ Error en inserción masiva de {module_name}: {{str(e)}}")
@@ -3179,7 +3901,7 @@ configure_image_generator(
3179
  module_names = [m['name'] for m in mock_modules]
3180
 
3181
  return f'''#!/usr/bin/env python3
3182
- \"\"\"Script para poblar la base de datos con datos iniciales - VERSIÓN CORREGIDA SIN ELIMINAR CAMPOS ESENCIALES\"\"\"
3183
 
3184
  import sys
3185
  import os
@@ -3195,10 +3917,11 @@ import models
3195
  {imports_str}
3196
 
3197
  def populate_initial_data():
3198
- \"\"\"Poblar la base de datos con datos iniciales - IDs generados automáticamente por la BD\"\"\"
3199
  print("🚀 Iniciando población de base de datos...")
3200
  print("💡 NOTA: Todos los IDs serán generados automáticamente por la base de datos")
3201
  print("✅ TODOS los campos financieros y fechas se preservarán (subtotal, iva, descuento, total, fechas)")
 
3202
 
3203
  print("🗄️ Creando tablas...")
3204
  try:
@@ -3214,8 +3937,40 @@ def populate_initial_data():
3214
 
3215
  print("\\n🎉 Proceso de población completado!")
3216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3217
  print("\\n📊 RESUMEN FINAL:")
3218
- print("=" * 50)
3219
 
3220
  total_records = 0
3221
  for module_name in {module_names}:
@@ -3229,8 +3984,10 @@ def populate_initial_data():
3229
  except Exception as e:
3230
  print(f" ❌ {{module_name.capitalize():.<15}} Error: {{e}}")
3231
 
3232
- print("=" * 50)
3233
- print(f" 📈 TOTAL: {{total_records:>23}} registros")
 
 
3234
 
3235
  # ✅ VERIFICACIÓN DE CAMPOS FINANCIEROS EN MÓDULOS CLAVE
3236
  print("\\n💰 VERIFICACIÓN DE CAMPOS FINANCIEROS:")
@@ -3274,6 +4031,12 @@ def populate_initial_data():
3274
  except Exception as e:
3275
  print(f" ℹ️ No se pudieron verificar usuarios del sistema: {{e}}")
3276
 
 
 
 
 
 
 
3277
  except Exception as e:
3278
  print(f"💥 Error general en población: {{str(e)}}")
3279
  db.rollback()
@@ -5588,5 +6351,4 @@ Si encuentras algún problema o tienes preguntas:
5588
 
5589
  # Reemplazar la función generate_readme original
5590
  def generate_readme(**kwargs):
5591
- return generate_complete_readme(**kwargs)
5592
-
 
121
 
122
  modules = []
123
 
124
+ # ✅✅✅ CORRECCIÓN: AGREGAR MÓDULO USUARIOS AUTOMÁTICAMENTE SI JWT ESTÁ ACTIVADO
125
+ if include_auth:
126
+ # Verificar que no exista ya un módulo 'usuarios' en los módulos que se agregarán
127
+ existing_module_names = [m['name'] for m in modules]
128
+ if 'usuarios' not in existing_module_names:
129
+ modules.append({
130
+ 'name': 'usuarios',
131
+ 'route': '/api/usuarios',
132
+ 'source': 'system', # Nuevo tipo para módulos del sistema
133
+ 'type': 'usuarios',
134
+ 'record_count': 50,
135
+ 'include_images': False,
136
+ 'image_source': None,
137
+ 'categorias_seleccionadas': []
138
+ })
139
+ st.success("✅ Módulo de usuarios creado automáticamente para autenticación JWT")
140
+
141
+ # EL RESTO DEL CÓDIGO SE MANTIENE IGUAL...
142
  if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
143
  if st.session_state.get('global_df') is not None:
144
  df = st.session_state.global_df
 
300
  st.metric("Tecnología", technology.split(" ")[0])
301
 
302
  with summary_col2:
303
+ # ✅✅✅ CORRECCIÓN: Error de sintaxis corregido - faltaba cerrar el paréntesis
304
  st.metric("Base de datos", database.split(" ")[0])
305
  st.metric("Autenticación", "Sí" if include_auth else "No")
306
 
 
361
  file_name=f"{project_name}.zip",
362
  mime="application/zip",
363
  use_container_width=True
 
364
  )
365
 
366
  with st.expander("🔗 Endpoints Generados", expanded=True):
 
369
  except Exception as e:
370
  st.error(f"❌ Error generando API: {str(e)}")
371
  st.error("💡 Revisa la configuración y vuelve a intentar")
372
+
373
+ # def show():
374
+ # st.header("⚡ Generador de API Profesional - E-commerce")
375
+
376
+ # # Configuración de API Keys - ACTUALIZADA CON PIXABAY
377
+ # with st.expander("🔑 Configuración de APIs Externas", expanded=False):
378
+ # # Valores por defecto para ambas APIs
379
+ # if 'pixabay_api_key' not in st.session_state:
380
+ # st.session_state['pixabay_api_key'] = "52812318-583c94721ffbb74a4f0c5684d"
381
+
382
+ # if 'pexels_api_key' not in st.session_state:
383
+ # st.session_state['pexels_api_key'] = "jPUxO9Zkb1OzitGkAmI9PeTe3oxqipfsYI3vdfCm0pg8QHFpUeSqVsNS"
384
+
385
+ # col1, col2 = st.columns(2)
386
+
387
+ # with col1:
388
+ # pixabay_api_key = st.text_input(
389
+ # "API Key de Pixabay 🥇:",
390
+ # value=st.session_state['pixabay_api_key'],
391
+ # type="password",
392
+ # help="Obtén tu API key gratis en https://pixabay.com/api/docs/"
393
+ # )
394
+ # st.session_state['pixabay_api_key'] = pixabay_api_key
395
+
396
+ # with col2:
397
+ # pexels_api_key = st.text_input(
398
+ # "API Key de Pexels 🥈:",
399
+ # value=st.session_state['pexels_api_key'],
400
+ # type="password",
401
+ # help="Obtén tu API key gratis en https://www.pexels.com/api/"
402
+ # )
403
+ # st.session_state['pexels_api_key'] = pexels_api_key
404
+
405
+ # # ✅✅✅ CORREGIDO: Inyectar AMBAS API keys ANTES de generar cualquier dato
406
+ # from utils.image_generator import configure_image_generator
407
+ # configure_image_generator(
408
+ # pexels_api_key=st.session_state['pexels_api_key'],
409
+ # pixabay_api_key=st.session_state['pixabay_api_key']
410
+ # )
411
+
412
+ # # ✅ Verificar que las API keys se configuraron correctamente
413
+ # from utils.image_generator import image_generator
414
+ # apis_configuradas = []
415
+
416
+ # if image_generator.pixabay_api_key and image_generator.pixabay_api_key != "TU_API_KEY_PIXABAY_AQUI":
417
+ # apis_configuradas.append("🥈 Pixabay") # Cambiado a 🥈
418
+
419
+ # if image_generator.pexels_api_key and image_generator.pexels_api_key != "TU_API_KEY_PEXELS_AQUI":
420
+ # apis_configuradas.append("🥉 Pexels") # Cambiado a 🥉
421
+
422
+ # # ✅ AGREGADO: Verificar Lexica (siempre disponible)
423
+ # apis_configuradas.append("🥇 Lexica")
424
+
425
+ # if apis_configuradas:
426
+ # st.success(f"✅ APIs configuradas: {', '.join(apis_configuradas)}")
427
+ # else:
428
+ # st.warning("⚠️ No hay APIs configuradas - Se usarán placeholders e IA")
429
+
430
+ # # Verificar datos globales
431
+ # if st.session_state.get('global_df') is None:
432
+ # st.warning("📤 No hay datos cargados en el sistema")
433
+ # st.info("💡 Carga un archivo en la barra lateral para generar API desde datos reales, o usa datos mock")
434
+
435
+ # st.subheader("🎯 Configuración de la API")
436
+
437
+ # # CONFIGURACIÓN PRINCIPAL
438
+ # col1, col2 = st.columns(2)
439
+
440
+ # with col1:
441
+ # api_type = st.radio(
442
+ # "Tipo de API:",
443
+ # ["🚀 Desde datos cargados", "🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"],
444
+ # help="Genera API desde tus datos, con datos de prueba, o combinando ambos"
445
+ # )
446
+
447
+ # technology = st.selectbox(
448
+ # "Tecnología del backend:",
449
+ # ["FastAPI (Python - Recomendado)", "Flask (Python)", "Django (Python)", "Spring Boot (Java)", "Express.js (Node.js)"],
450
+ # index=0
451
+ # )
452
+
453
+ # database = st.selectbox(
454
+ # "Base de datos:",
455
+ # ["SQLite (Desarrollo)", "PostgreSQL (Producción)", "MySQL (Producción)", "MongoDB (NoSQL)"],
456
+ # index=0
457
+ # )
458
+
459
+ # with col2:
460
+ # project_name = st.text_input(
461
+ # "Nombre del proyecto:",
462
+ # value="mi_api_ecommerce",
463
+ # help="Nombre de la carpeta y proyecto"
464
+ # )
465
+
466
+ # api_version = st.text_input(
467
+ # "Versión de la API:",
468
+ # value="1.0.0",
469
+ # help="Versión semántica (ej: 1.0.0)"
470
+ # )
471
+
472
+ # include_auth = st.checkbox("🔐 Incluir autenticación JWT", value=True)
473
+ # include_docs = st.checkbox("📚 Incluir documentación Swagger", value=True)
474
+ # include_docker = st.checkbox("🐳 Incluir Docker y Docker Compose", value=True)
475
+
476
+ # # CONFIGURACIÓN DE MÓDULOS/ENTIDADES
477
+ # st.subheader("🏗️ Módulos de la API E-commerce")
478
+
479
+ # modules = []
480
+
481
+ # if api_type in ["🚀 Desde datos cargados", "🔗 API Híbrida (datos reales + mock)"]:
482
+ # if st.session_state.get('global_df') is not None:
483
+ # df = st.session_state.global_df
484
+ # filename = st.session_state.global_filename
485
+
486
+ # st.success(f"📊 Datos cargados: {filename}")
487
+
488
+ # main_entity = infer_entity_name(filename)
489
+
490
+ # with st.expander(f"🔧 Configurar módulo: {main_entity}", expanded=True):
491
+ # module_name = st.text_input("Nombre del módulo:", value=main_entity, key="main_module")
492
+ # base_route = st.text_input("Ruta base:", value=f"/{main_entity}", key="main_route")
493
+
494
+ # st.write("**Configuración de campos:**")
495
+ # field_config = {}
496
+ # for col in df.columns:
497
+ # col1, col2, col3 = st.columns([2, 2, 1])
498
+ # with col1:
499
+ # field_name = st.text_input("Nombre campo:", value=col, key=f"field_{col}_name")
500
+ # with col2:
501
+ # field_type = st.selectbox(
502
+ # "Tipo:",
503
+ # ["string", "integer", "float", "boolean", "datetime", "email", "url"],
504
+ # key=f"field_{col}_type"
505
+ # )
506
+ # with col3:
507
+ # required = st.checkbox("Requerido", value=True, key=f"field_{col}_req")
508
+
509
+ # field_config[col] = {
510
+ # 'name': field_name,
511
+ # 'type': field_type,
512
+ # 'required': required
513
+ # }
514
+
515
+ # modules.append({
516
+ # 'name': module_name,
517
+ # 'route': base_route,
518
+ # 'source': 'file',
519
+ # 'data': df,
520
+ # 'fields': field_config
521
+ # })
522
+
523
+ # # Agregar módulos adicionales para API Mock
524
+ # if api_type in ["🎭 API Mock (datos de prueba)", "🔗 API Híbrida (datos reales + mock)"]:
525
+ # st.write("---")
526
+ # st.write("**➕ Agregar módulos mock para E-commerce**")
527
+
528
+ # # MÓDULOS ESENCIALES vs OPCIONALES
529
+ # essential_modules = ["usuarios", "productos", "categorias", "pedidos", "carrito"]
530
+ # optional_modules = ["pagos", "reseñas", "direcciones", "cupones"]
531
+
532
+ # col_ess, col_opt = st.columns(2)
533
+
534
+ # with col_ess:
535
+ # st.write("**🎯 Módulos Esenciales**")
536
+ # essential_selected = st.multiselect(
537
+ # "Seleccionar módulos esenciales:",
538
+ # essential_modules,
539
+ # default=essential_modules,
540
+ # label_visibility="collapsed"
541
+ # )
542
+
543
+ # with col_opt:
544
+ # st.write("**🔧 Módulos Opcionales**")
545
+ # optional_selected = st.multiselect(
546
+ # "Seleccionar módulos opcionales:",
547
+ # optional_modules,
548
+ # default=["pagos", "reseñas"],
549
+ # label_visibility="collapsed"
550
+ # )
551
+
552
+ # mock_modules = essential_selected + optional_selected
553
+
554
+ # for module in mock_modules:
555
+ # with st.expander(f"🎭 Configurar módulo: {module}", expanded=False):
556
+ # module_name = st.text_input("Nombre:", value=module, key=f"mock_{module}_name")
557
+ # base_route = st.text_input("Ruta:", value=f"/{module}", key=f"mock_{module}_route")
558
+ # record_count = st.slider("Número de registros:", 10, 1000, 50, key=f"mock_{module}_count")
559
+
560
+ # # Configuración específica por módulo
561
+ # if module in ["productos"]:
562
+ # include_images = st.checkbox("🖼️ Incluir imágenes reales", value=True, key=f"mock_{module}_images")
563
+ # image_source = st.selectbox(
564
+ # "Fuente de imágenes:",
565
+ # [
566
+ # "🥇 Lexica (Búsquedas específicas con IA)", # PRIMERA
567
+ # "🥈 Pollinations AI (Generadas por IA)", # SEGUNDA
568
+ # "🥉 Pixabay (Precisas, libres de derechos)", # TERCERA
569
+ # "📸 Pexels (Alta calidad)", # CUARTA
570
+ # "🪄 Placeholder (Último recurso)",
571
+ # "🎯 Orden de prioridad automático"
572
+ # ],
573
+ # key=f"mock_{module}_imgsrc"
574
+ # )
575
+
576
+ # categorias_disponibles = [
577
+ # 'Electrónica', 'Tecnología', 'Hogar', 'Ropa', 'Deportes',
578
+ # 'Juguetes', 'Libros', 'Música', 'Belleza', 'Salud',
579
+ # 'Alimentos', 'Bebidas', 'Automotriz', 'Jardín', 'Oficina',
580
+ # 'Comidas Dulces', 'Comidas Saladas', 'Bebidas'
581
+ # ]
582
+
583
+ # categorias_seleccionadas = st.multiselect(
584
+ # f"Categorías de {module}:",
585
+ # categorias_disponibles,
586
+ # default=categorias_disponibles[:5],
587
+ # key=f"mock_{module}_cats"
588
+ # )
589
+
590
+ # if categorias_seleccionadas and any(cat in ['Comidas Dulces', 'Comidas Saladas', 'Bebidas'] for cat in categorias_seleccionadas):
591
+ # st.success("🍽️ **Modo Restaurante Activado**: Se generarán productos especializados (tortas, hamburguesas, bebidas, etc.)")
592
+ # else:
593
+ # include_images = False
594
+ # image_source = None
595
+ # categorias_seleccionadas = []
596
+
597
+ # modules.append({
598
+ # 'name': module_name,
599
+ # 'route': base_route,
600
+ # 'source': 'mock',
601
+ # 'type': module,
602
+ # 'record_count': record_count,
603
+ # 'include_images': include_images,
604
+ # 'image_source': image_source,
605
+ # 'categorias_seleccionadas': categorias_seleccionadas
606
+ # })
607
+
608
+ # # CONFIGURACIÓN AVANZADA
609
+ # st.subheader("⚙️ Configuración Avanzada")
610
+
611
+ # adv_col1, adv_col2 = st.columns(2)
612
+
613
+ # with adv_col1:
614
+ # cors_enabled = st.checkbox("🌐 Habilitar CORS", value=True)
615
+ # rate_limiting = st.checkbox("⏱️ Rate Limiting", value=True)
616
+ # file_uploads = st.checkbox("📁 Manejo de archivos", value=True)
617
+ # include_migrations = st.checkbox("🔄 Migraciones Alembic", value=True)
618
+ # pagination_size = st.slider("Tamaño de paginación:", 10, 100, 25)
619
+
620
+ # with adv_col2:
621
+ # logging_level = st.selectbox("Nivel de logging:", ["DEBUG", "INFO", "WARNING", "ERROR"])
622
+ # include_tests = st.checkbox("🧪 Incluir tests automatizados", value=True)
623
+ # generate_sdk = st.checkbox("📦 Generar SDK cliente", value=True)
624
+ # populate_db = st.checkbox("🌱 Poblar BD con datos mock", value=True)
625
+
626
+ # # GENERACIÓN DE LA API
627
+ # st.subheader("🎉 Generar API")
628
+
629
+ # if not modules:
630
+ # st.warning("Agrega al menos un módulo para generar la API")
631
+ # return
632
+
633
+ # # Mostrar resumen
634
+ # st.write("### 📋 Resumen de la API")
635
+ # summary_col1, summary_col2, summary_col3 = st.columns(3)
636
+
637
+ # with summary_col1:
638
+ # st.metric("Módulos", len(modules))
639
+ # st.metric("Tecnología", technology.split(" ")[0])
640
+
641
+ # with summary_col2:
642
+ # st.metric("Base de datos", database.split(" ")[0])
643
+ # st.metric("Autenticación", "Sí" if include_auth else "No")
644
+
645
+ # with summary_col3:
646
+ # total_records = sum([mod.get('record_count', len(mod.get('data', []))) for mod in modules])
647
+ # st.metric("Registros totales", total_records)
648
+ # st.metric("Docker", "Sí" if include_docker else "No")
649
+
650
+ # # Información del sistema de imágenes - ACTUALIZADA CON LEXICA
651
+ # with st.expander("📸 Sistema de Imágenes Configurado", expanded=False):
652
+ # st.write("**🎯 Orden de Prioridad:**")
653
+ # st.write("1. 🥇 **Lexica** - Búsquedas específicas con AI (Siempre disponible)")
654
+ # st.write("2. 🥈 **Pollinations** - Imágenes generadas por IA coherentes")
655
+ # st.write("3. 🥉 **Pixabay** - Fotos reales libres de derechos")
656
+ # st.write("4. 📸 **Pexels** - Backup con calidad alta")
657
+ # st.write("5. 🪄 **Placeholder** - Último recurso (Siempre disponible)")
658
+
659
+ # st.info("**💡 Orden automático:** Lexica → Pollinations → Pixabay → Pexels → Placeholder")
660
+
661
+ # if apis_configuradas:
662
+ # st.success(f"**APIs Configuradas:** {', '.join(apis_configuradas)}")
663
+ # else:
664
+ # st.info("**Modo automático:** Se usará Lexica + Pollinations + Placeholders")
665
+
666
+ # if st.button("⚡ Generar API Completa", type="primary", use_container_width=True):
667
+ # with st.spinner("🚀 Generando API profesional para E-commerce..."):
668
+ # try:
669
+ # api_structure = generate_complete_api(
670
+ # project_name=project_name,
671
+ # technology=technology,
672
+ # database=database,
673
+ # modules=modules,
674
+ # include_auth=include_auth,
675
+ # include_docs=include_docs,
676
+ # include_docker=include_docker,
677
+ # api_version=api_version,
678
+ # cors_enabled=cors_enabled,
679
+ # rate_limiting=rate_limiting,
680
+ # file_uploads=file_uploads,
681
+ # include_migrations=include_migrations,
682
+ # pagination_size=pagination_size,
683
+ # include_tests=include_tests,
684
+ # generate_sdk=generate_sdk,
685
+ # logging_level=logging_level,
686
+ # populate_db=populate_db
687
+ # )
688
+
689
+ # zip_buffer = create_api_zip(api_structure, project_name)
690
+
691
+ # st.success("✅ API generada exitosamente!")
692
+
693
+ # with st.expander("🚀 Instrucciones de Despliegue", expanded=True):
694
+ # show_deployment_instructions(technology, database, project_name)
695
+
696
+ # st.download_button(
697
+ # label="📥 Descargar API Completa",
698
+ # data=zip_buffer,
699
+ # file_name=f"{project_name}.zip",
700
+ # mime="application/zip",
701
+ # use_container_width=True
702
+ # # ❌ NO usar on_click - ya registramos la métrica al generar
703
+ # )
704
+
705
+ # with st.expander("🔗 Endpoints Generados", expanded=True):
706
+ # show_generated_endpoints(modules)
707
+
708
+ # except Exception as e:
709
+ # st.error(f"❌ Error generando API: {str(e)}")
710
+ # st.error("💡 Revisa la configuración y vuelve a intentar")
711
 
712
  # CONTINUARÁ EN LA SIGUIENTE PARTE...
713
  # CONTINUACIÓN DE api_generator.py
 
974
  "utils/rate_limit.py": generate_rate_limit_utils(**kwargs) if kwargs['rate_limiting'] else "",
975
  "utils/file_upload.py": generate_file_upload_utils(**kwargs) if kwargs['file_uploads'] else "",
976
  "utils/image_generator.py": generate_image_generator_utils(**kwargs),
977
+ "utils/backup_manager.py": generate_backup_manager(**kwargs),
978
 
979
  # Scripts
980
  "scripts/__init__.py": "",
 
1790
  return image_generator
1791
  '''
1792
 
1793
+ ####agregada
1794
+ def generate_backup_manager(**kwargs):
1795
+ """Generar el archivo backup_manager.py para el sistema de respaldos JSON"""
1796
+
1797
+ return '''import json
1798
+ import os
1799
+ from datetime import datetime
1800
+ from typing import List, Dict, Any, Optional
1801
+ from sqlalchemy.orm import Session
1802
+ import logging
1803
+
1804
+ class BackupManager:
1805
+ """
1806
+ Sistema de respaldo automático en JSON para todas las entidades de la base de datos.
1807
+ Genera archivos JSON individuales por cada entidad y se actualiza automáticamente.
1808
+ """
1809
+
1810
+ def __init__(self, backup_dir: str = "backups/json"):
1811
+ self.backup_dir = backup_dir
1812
+ self.setup_backup_structure()
1813
+ self.setup_logging()
1814
+ print(f"🔧 BackupManager inicializado - Directorio: {backup_dir}")
1815
+
1816
+ def setup_backup_structure(self):
1817
+ """Crear estructura de directorios para backups"""
1818
+ os.makedirs(self.backup_dir, exist_ok=True)
1819
+ os.makedirs(f"{self.backup_dir}/logs", exist_ok=True)
1820
+ print(f"📁 Estructura de backups creada: {self.backup_dir}")
1821
+
1822
+ def setup_logging(self):
1823
+ """Configurar logging para backups"""
1824
+ logging.basicConfig(
1825
+ filename=f"{self.backup_dir}/logs/backup.log",
1826
+ level=logging.INFO,
1827
+ format='%(asctime)s - %(levelname)s - %(message)s',
1828
+ encoding='utf-8'
1829
+ )
1830
+ self.logger = logging.getLogger(__name__)
1831
+
1832
+ def export_entity_to_json(self, db: Session, model_class, entity_name: str) -> bool:
1833
+ """
1834
+ Exportar una entidad específica a JSON
1835
+
1836
+ Args:
1837
+ db: Sesión de base de datos
1838
+ model_class: Clase del modelo SQLAlchemy
1839
+ entity_name: Nombre de la entidad (para el archivo)
1840
+
1841
+ Returns:
1842
+ bool: True si fue exitoso, False si hubo error
1843
+ """
1844
+ try:
1845
+ # Obtener todos los registros de la entidad
1846
+ records = db.query(model_class).all()
1847
+
1848
+ # Convertir registros a diccionario
1849
+ data = []
1850
+ for record in records:
1851
+ record_dict = {}
1852
+ for column in record.__table__.columns:
1853
+ value = getattr(record, column.name)
1854
+
1855
+ # Convertir tipos especiales a formato serializable
1856
+ if hasattr(value, 'isoformat'): # datetime, date
1857
+ value = value.isoformat()
1858
+ elif value is None:
1859
+ value = None
1860
+ elif isinstance(value, (int, float, str, bool)):
1861
+ value = value
1862
+ else:
1863
+ value = str(value) # Fallback para otros tipos
1864
+
1865
+ record_dict[column.name] = value
1866
+ data.append(record_dict)
1867
+
1868
+ # Estructura del archivo JSON
1869
+ backup_data = {
1870
+ "metadata": {
1871
+ "entity": entity_name,
1872
+ "export_date": datetime.now().isoformat(),
1873
+ "record_count": len(data),
1874
+ "database_timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
1875
+ },
1876
+ "data": data
1877
+ }
1878
+
1879
+ # Guardar en archio JSON
1880
+ backup_file = f"{self.backup_dir}/{entity_name}.json"
1881
+ with open(backup_file, 'w', encoding='utf-8') as f:
1882
+ json.dump(backup_data, f, indent=2, ensure_ascii=False, default=str)
1883
+
1884
+ self.logger.info(f"✅ Backup completado: {entity_name} - {len(data)} registros")
1885
+ print(f"💾 Backup actualizado: {entity_name}.json ({len(data)} registros)")
1886
+ return True
1887
+
1888
+ except Exception as e:
1889
+ error_msg = f"❌ Error en backup de {entity_name}: {str(e)}"
1890
+ self.logger.error(error_msg)
1891
+ print(error_msg)
1892
+ return False
1893
+
1894
+ def export_all_entities(self, db: Session, models_dict: Dict[str, Any]) -> Dict[str, bool]:
1895
+ """
1896
+ Exportar todas las entidades a JSON
1897
+
1898
+ Args:
1899
+ db: Sesión de base de datos
1900
+ models_dict: Diccionario con {nombre_entidad: clase_modelo}
1901
+
1902
+ Returns:
1903
+ Dict: Resultados por entidad {entidad: éxito}
1904
+ """
1905
+ print("🔄 Iniciando exportación completa de backups...")
1906
+ results = {}
1907
+
1908
+ for entity_name, model_class in models_dict.items():
1909
+ success = self.export_entity_to_json(db, model_class, entity_name)
1910
+ results[entity_name] = success
1911
+
1912
+ # Estadísticas
1913
+ successful = sum(results.values())
1914
+ total = len(results)
1915
+ print(f"📊 Exportación completada: {successful}/{total} entidades respaldadas")
1916
+
1917
+ return results
1918
+
1919
+ def get_backup_status(self) -> Dict[str, Any]:
1920
+ """
1921
+ Obtener estado actual de todos los backups
1922
+
1923
+ Returns:
1924
+ Dict: Información de todos los archivos de backup
1925
+ """
1926
+ backups = {}
1927
+ total_size_kb = 0
1928
+
1929
+ if os.path.exists(self.backup_dir):
1930
+ for file in os.listdir(self.backup_dir):
1931
+ if file.endswith('.json') and not file.startswith('.'):
1932
+ file_path = os.path.join(self.backup_dir, file)
1933
+ try:
1934
+ file_stats = os.stat(file_path)
1935
+ entity_name = file.replace('.json', '')
1936
+
1937
+ # Leer metadata del archivo JSON
1938
+ metadata = {}
1939
+ try:
1940
+ with open(file_path, 'r', encoding='utf-8') as f:
1941
+ backup_data = json.load(f)
1942
+ metadata = backup_data.get('metadata', {})
1943
+ except:
1944
+ metadata = {"error": "No se pudo leer metadata"}
1945
+
1946
+ backups[entity_name] = {
1947
+ "file": file,
1948
+ "size_kb": round(file_stats.st_size / 1024, 2),
1949
+ "modified": datetime.fromtimestamp(file_stats.st_mtime).isoformat(),
1950
+ "record_count": metadata.get('record_count', 0),
1951
+ "last_export": metadata.get('export_date', 'N/A')
1952
+ }
1953
+ total_size_kb += file_stats.st_size / 1024
1954
+ except Exception as e:
1955
+ backups[file] = {"error": str(e)}
1956
+
1957
+ return {
1958
+ "backups": backups,
1959
+ "summary": {
1960
+ "total_files": len(backups),
1961
+ "total_size_kb": round(total_size_kb, 2),
1962
+ "backup_directory": self.backup_dir,
1963
+ "timestamp": datetime.now().isoformat()
1964
+ }
1965
+ }
1966
+
1967
+ def backup_after_operation(self, db: Session, model_class, entity_name: str):
1968
+ """
1969
+ Ejecutar backup después de una operación CRUD
1970
+ Versión optimizada para no bloquear la respuesta
1971
+ """
1972
+ try:
1973
+ # Ejecutar en segundo plano (no bloqueante)
1974
+ self.export_entity_to_json(db, model_class, entity_name)
1975
+ except Exception as e:
1976
+ self.logger.error(f"❌ Error en backup automático de {entity_name}: {str(e)}")
1977
+
1978
+ def get_entity_backup(self, entity_name: str) -> Optional[Dict]:
1979
+ """
1980
+ Obtener datos de backup de una entidad específica
1981
+
1982
+ Args:
1983
+ entity_name: Nombre de la entidad
1984
+
1985
+ Returns:
1986
+ Dict: Datos del backup o None si no existe
1987
+ """
1988
+ backup_file = f"{self.backup_dir}/{entity_name}.json"
1989
+ if os.path.exists(backup_file):
1990
+ try:
1991
+ with open(backup_file, 'r', encoding='utf-8') as f:
1992
+ return json.load(f)
1993
+ except Exception as e:
1994
+ self.logger.error(f"❌ Error leyendo backup {entity_name}: {str(e)}")
1995
+ return None
1996
+ return None
1997
 
1998
+ # Instancia global para usar en toda la aplicación
1999
+ backup_manager = BackupManager()
2000
+
2001
+ # Funciones de conveniencia para importar fácilmente
2002
+ def get_backup_manager() -> BackupManager:
2003
+ return backup_manager
2004
+
2005
+ def configure_backup_manager(backup_dir: str = "backups/json") -> BackupManager:
2006
+ global backup_manager
2007
+ backup_manager = BackupManager(backup_dir)
2008
+ return backup_manager
2009
+ '''
2010
 
2011
  # CONTINUARÁ EN LA PARTE 3...
2012
  # PARTE 3: Modelos y Schemas Corregidos
 
2513
  # PARTE 4: Routers y Endpoints Corregidos
2514
 
2515
  def generate_fastapi_router(module, **kwargs):
2516
+ """Generar router para un módulo en FastAPI - VERSIÓN CON BACKUPS"""
2517
 
2518
  module_name = module['name']
2519
  class_name = module_name.capitalize()
 
2540
  from database import get_db
2541
  from models.{module_name} import {class_name}
2542
  from schemas.{module_name} import {schema_name}, {schema_name}Create, {schema_name}Update
2543
+ from utils.backup_manager import backup_manager # ✅ NUEVO: Importar backup manager
2544
 
2545
  router = APIRouter()
2546
 
 
2576
  db.add(db_{module_name.rstrip('s')})
2577
  db.commit()
2578
  db.refresh(db_{module_name.rstrip('s')})
2579
+
2580
+ # ✅ NUEVO: Backup automático después de crear
2581
+ backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2582
+
2583
  return db_{module_name.rstrip('s')}
2584
  except Exception as e:
2585
  db.rollback()
 
2603
 
2604
  db.commit()
2605
  db.refresh(db_{module_name.rstrip('s')})
2606
+
2607
+ # ✅ NUEVO: Backup autom��tico después de actualizar
2608
+ backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2609
+
2610
  return db_{module_name.rstrip('s')}
2611
  except Exception as e:
2612
  db.rollback()
 
2625
  try:
2626
  db.delete(db_{module_name.rstrip('s')})
2627
  db.commit()
2628
+
2629
+ # ✅ NUEVO: Backup automático después de eliminar
2630
+ backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2631
+
2632
  return None
2633
  except Exception as e:
2634
  db.rollback()
 
2643
  ):
2644
  """Buscar {module_name} por término"""
2645
  try:
2646
+ # ✅ MEJORADO: Búsqueda más robusta en múltiples campos
2647
+ from sqlalchemy import or_
2648
+
2649
+ # Determinar campos de búsqueda según el tipo de módulo
2650
+ search_fields = []
2651
+ if hasattr({class_name}, 'nombre'):
2652
+ search_fields.append({class_name}.nombre.ilike(f"%{{q}}%"))
2653
+ if hasattr({class_name}, 'descripcion'):
2654
+ search_fields.append({class_name}.descripcion.ilike(f"%{{q}}%"))
2655
+ if hasattr({class_name}, 'email'):
2656
+ search_fields.append({class_name}.email.ilike(f"%{{q}}%"))
2657
+
2658
+ if search_fields:
2659
+ {module_name} = db.query({class_name}).filter(or_(*search_fields)).offset(skip).limit(limit).all()
2660
+ else:
2661
+ # Fallback: buscar en todos los campos string
2662
+ {module_name} = db.query({class_name}).offset(skip).limit(limit).all()
2663
+
2664
  return {module_name}
2665
  except Exception as e:
2666
  raise HTTPException(status_code=400, detail=f"Error en búsqueda: {{str(e)}}")
 
2724
  try:
2725
  db.query({class_name}).filter({class_name}.usuario_id == usuario_id).delete()
2726
  db.commit()
2727
+
2728
+ # ✅ NUEVO: Backup automático después de limpiar carrito
2729
+ backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2730
+
2731
  return None
2732
  except Exception as e:
2733
  db.rollback()
 
2762
  pedido.estado = estado
2763
  db.commit()
2764
  db.refresh(pedido)
2765
+
2766
+ # ✅ NUEVO: Backup automático después de cambiar estado
2767
+ backup_manager.backup_after_operation(db, {class_name}, "{module_name}")
2768
+
2769
  return pedido
2770
  '''
2771
 
 
2919
 
2920
 
2921
  def generate_fastapi_main(**kwargs):
2922
+ """Generar archivo main.py - VERSIÓN CORREGIDA CON PERSISTENCIA Y BACKUPS"""
2923
 
2924
  project_name = kwargs['project_name']
2925
  api_version = kwargs['api_version']
 
2932
  imports = [
2933
  "from fastapi import FastAPI, Depends, HTTPException, Request",
2934
  "from fastapi.middleware.cors import CORSMiddleware",
2935
+ "from fastapi.responses import JSONResponse, FileResponse",
2936
  "from contextlib import asynccontextmanager",
2937
  "import uvicorn",
2938
+ "from database import get_db, create_tables, engine", # ✅ CORREGIDO: agregar engine
2939
  "from datetime import datetime",
2940
  "import traceback",
2941
  "import sys",
 
2945
  # ✅ AGREGAR IMPORT PARA VERIFICAR TABLAS EXISTENTES
2946
  imports.append("from sqlalchemy import inspect")
2947
 
2948
+ # ✅ AGREGAR IMPORTS PARA BACKUPS
2949
+ imports.append("from fastapi.staticfiles import StaticFiles")
2950
+
2951
  if kwargs['include_auth']:
2952
  imports.append("from routers.auth import router as auth_router")
2953
 
 
3031
  print("🛑 Apagando API...")
3032
  print("👋 Hasta pronto!")'''
3033
 
3034
+ # ✅ CORREGIDO: Evitar rutas duplicadas con doble "api"
3035
  router_includes = ""
3036
  if kwargs['include_auth']:
3037
  router_includes += 'app.include_router(auth_router, prefix="/api/v1/auth", tags=["auth"])\n'
3038
 
3039
  for module in modules:
3040
+ # ✅ CORRECCIÓN: Normalizar rutas para evitar /api/v1/api/usuarios
3041
+ route = module["route"]
3042
+ # Si la ruta ya empieza con /api/, quitar el /api/ inicial
3043
+ if route.startswith("/api/"):
3044
+ route = route[4:] # Remover "/api" del inicio
3045
+ elif route.startswith("api/"):
3046
+ route = route[3:] # Remover "api" del inicio
3047
+
3048
+ # Asegurar que la ruta empiece con /
3049
+ if not route.startswith("/"):
3050
+ route = "/" + route
3051
+
3052
+ router_includes += f'app.include_router({module["name"]}_router, prefix="/api/v1{route}", tags=["{module["name"]}"])\n'
3053
 
3054
  return f'''{imports_str}
3055
 
 
3057
 
3058
  app = FastAPI(
3059
  title="{project_name.replace('_', ' ').title()}",
3060
+ description="API profesional para E-commerce generada automáticamente - CON PERSISTENCIA DE DATOS Y BACKUPS JSON",
3061
  version="{api_version}",
3062
  docs_url="/docs" if {kwargs['include_docs']} else None,
3063
  redoc_url="/redoc" if {kwargs['include_docs']} else None,
 
3073
  )
3074
 
3075
  {router_includes}
3076
+
3077
+ # ✅ SISTEMA DE BACKUPS JSON - Montar directorio estático
3078
+ @app.on_event("startup")
3079
+ async def startup_backup_system():
3080
+ """Inicializar sistema de backups al iniciar la aplicación"""
3081
+ backup_dir = "backups/json"
3082
+ if not os.path.exists(backup_dir):
3083
+ os.makedirs(backup_dir, exist_ok=True)
3084
+ print(f"📁 Directorio de backups creado: {{backup_dir}}")
3085
+
3086
+ # Montar directorio de backups como estático (SOLO DESARROLLO)
3087
+ if os.path.exists(backup_dir):
3088
+ app.mount("/backups", StaticFiles(directory=backup_dir), name="backups")
3089
+ print("🔗 Backups disponibles en: http://localhost:8000/backups/")
3090
+
3091
  @app.get("/")
3092
  async def root():
3093
  return {{
3094
+ "message": "🚀 Bienvenido a {project_name} API - Sistema E-commerce CON PERSISTENCIA Y BACKUPS",
3095
  "version": "{api_version}",
3096
  "status": "operational",
3097
  "timestamp": datetime.utcnow().isoformat(),
3098
  "docs": "/docs" if {kwargs['include_docs']} else None,
3099
+ "backups": "/backups" if {kwargs['include_docs']} else None,
3100
  "modules": {module_names},
3101
  "features": {{
3102
  "authentication": {kwargs['include_auth']},
3103
  "documentation": {kwargs['include_docs']},
3104
  "docker": {kwargs['include_docker']},
3105
  "database": "{database}",
3106
+ "persistence": True,
3107
+ "json_backups": True # ✅ NUEVO: Backups JSON habilitados
3108
  }}
3109
  }}
3110
 
 
3121
  except Exception as e:
3122
  db_status = f"error: {{str(e)}}"
3123
 
3124
+ # ✅ VERIFICAR SISTEMA DE BACKUPS
3125
+ backup_status = "active"
3126
+ backup_dir = "backups/json"
3127
+ if not os.path.exists(backup_dir):
3128
+ backup_status = "directory_not_found"
3129
+ elif not os.access(backup_dir, os.W_OK):
3130
+ backup_status = "no_write_permission"
3131
+
3132
  return {{
3133
  "status": "healthy",
3134
  "timestamp": datetime.utcnow().isoformat(),
3135
  "service": "{project_name}",
3136
  "version": "{api_version}",
3137
  "database": db_status,
3138
+ "backups": backup_status, # ✅ NUEVO: Estado de backups
3139
+ "persistence": True
3140
  }}
3141
 
3142
  @app.get("/info")
 
3150
  "source": module.get('source', 'unknown')
3151
  }})
3152
 
3153
+ # ✅ MEJORADO: Información sobre persistencia y backups
3154
  persistence_info = {{
3155
  "database_persistent": True,
3156
  "data_safe": True,
3157
  "auto_populate": {kwargs['populate_db']},
3158
+ "json_backups": True, # ✅ NUEVO
3159
+ "backup_directory": "backups/json",
3160
+ "warning": "Los datos se mantienen entre reinicios y tienen respaldo JSON"
3161
  }}
3162
 
3163
  return {{
3164
  "name": "{project_name}",
3165
  "version": "{api_version}",
3166
+ "description": "API E-commerce generada automáticamente - DATOS PERSISTENTES CON BACKUPS JSON",
3167
  "modules": module_info,
3168
  "database": "{database}",
3169
  "authentication": {kwargs['include_auth']},
3170
  "documentation": {kwargs['include_docs']},
3171
+ "backups": True, # ✅ NUEVO
3172
+ "persistence": persistence_info,
3173
  "endpoints": {{
3174
  "root": "/",
3175
  "health": "/health",
3176
  "info": "/info",
3177
  "docs": "/docs" if {kwargs['include_docs']} else None,
3178
+ "backups": "/backups",
3179
+ "api_base": "/api/v1",
3180
+ "backup_api": "/api/v1/backups"
3181
  }}
3182
  }}
3183
 
3184
+ # ✅ ENDPOINTS DE BACKUP - Agregados después de los endpoints principales
3185
+ @app.get("/api/v1/backups/status")
3186
+ async def get_backup_status():
3187
+ """Obtener estado de los backups JSON"""
3188
+ backup_dir = "backups/json"
3189
+ backups = {{}}
3190
+
3191
+ if os.path.exists(backup_dir):
3192
+ for file in os.listdir(backup_dir):
3193
+ if file.endswith('.json'):
3194
+ file_path = os.path.join(backup_dir, file)
3195
+ file_stats = os.stat(file_path)
3196
+ backups[file] = {{
3197
+ "size_kb": round(file_stats.st_size / 1024, 2),
3198
+ "modified": datetime.fromtimestamp(file_stats.st_mtime).isoformat(),
3199
+ "entities": file.replace('.json', '')
3200
+ }}
3201
+
3202
+ return {{
3203
+ "status": "success",
3204
+ "backups": backups,
3205
+ "backup_count": len(backups),
3206
+ "timestamp": datetime.utcnow().isoformat(),
3207
+ "backup_directory": backup_dir
3208
+ }}
3209
+
3210
+ @app.get("/api/v1/backups/download/{{entity_name}}")
3211
+ async def download_backup(entity_name: str):
3212
+ """Descargar backup específico de una entidad"""
3213
+ backup_file = f"backups/json/{{entity_name}}.json"
3214
+ if os.path.exists(backup_file):
3215
+ return FileResponse(
3216
+ backup_file,
3217
+ media_type='application/json',
3218
+ filename=f"{{entity_name}}_backup.json"
3219
+ )
3220
+ raise HTTPException(status_code=404, detail=f"Backup no encontrado para entidad: {{entity_name}}")
3221
+
3222
+ @app.get("/backups")
3223
+ async def backups_info():
3224
+ """Página de información de backups (para navegador)"""
3225
+ return {{
3226
+ "message": "Sistema de Backups JSON",
3227
+ "description": "Backups automáticos de todas las entidades de la base de datos",
3228
+ "endpoints": {{
3229
+ "view_backups": "http://localhost:8000/backups/ (en navegador)",
3230
+ "api_status": "GET /api/v1/backups/status",
3231
+ "download": "GET /api/v1/backups/download/{{entity_name}}"
3232
+ }},
3233
+ "note": "Los backups se generan automáticamente después de cada operación CRUD"
3234
+ }}
3235
+
3236
  @app.exception_handler(500)
3237
  async def internal_server_error_handler(request: Request, exc: Exception):
3238
  return JSONResponse(
 
3271
  if __name__ == "__main__":
3272
  print("🎪 Iniciando servidor de desarrollo...")
3273
  print("📖 Documentación disponible en: http://localhost:8000/docs")
3274
+ print("💾 Backups JSON disponibles en: http://localhost:8000/backups/")
3275
  print("🔧 Modo: Desarrollo (Auto-reload activado)")
3276
  print("💾 MODO PERSISTENTE: Los datos se mantienen entre reinicios")
3277
+ print("📁 BACKUPS ACTIVOS: Respaldos JSON automáticos")
3278
 
3279
  uvicorn.run(
3280
  "main:app",
 
3710
  return mock_data_code
3711
 
3712
  def generate_populate_script(**kwargs):
3713
+ """Generar script para poblar la base de datos - VERSIÓN CON BACKUPS AUTOMÁTICOS"""
3714
 
3715
  mock_modules = [m for m in kwargs['modules'] if m['source'] == 'mock' and kwargs['populate_db']]
3716
 
 
3864
  print(f" ✅ {module_name} poblados exitosamente: {{added_count}} registros agregados")
3865
  if error_count > 0:
3866
  print(f" ⚠️ Se omitieron {{error_count}} registros debido a errores")
3867
+
3868
+ # ✅ NUEVO: GENERAR BACKUP DESPUÉS DE POBLAR CADA MÓDULO
3869
+ try:
3870
+ from utils.backup_manager import backup_manager
3871
+ backup_success = backup_manager.export_entity_to_json(db, model_class, "{module_name}")
3872
+ if backup_success:
3873
+ print(f" 💾 Backup JSON generado: {module_name}.json")
3874
+ else:
3875
+ print(f" ⚠️ Error generando backup de {module_name}")
3876
+ except Exception as backup_error:
3877
+ print(f" ⚠️ Error en sistema de backup: {{backup_error}}")
3878
+
3879
  except Exception as e:
3880
  db.rollback()
3881
  print(f" ❌ Error en inserción masiva de {module_name}: {{str(e)}}")
 
3901
  module_names = [m['name'] for m in mock_modules]
3902
 
3903
  return f'''#!/usr/bin/env python3
3904
+ \"\"\"Script para poblar la base de datos con datos iniciales - VERSIÓN CON BACKUPS AUTOMÁTICOS\"\"\"
3905
 
3906
  import sys
3907
  import os
 
3917
  {imports_str}
3918
 
3919
  def populate_initial_data():
3920
+ \"\"\"Poblar la base de datos con datos iniciales - CON BACKUPS JSON AUTOMÁTICOS\"\"\"
3921
  print("🚀 Iniciando población de base de datos...")
3922
  print("💡 NOTA: Todos los IDs serán generados automáticamente por la base de datos")
3923
  print("✅ TODOS los campos financieros y fechas se preservarán (subtotal, iva, descuento, total, fechas)")
3924
+ print("💾 BACKUPS: Se generarán archivos JSON automáticamente para cada entidad")
3925
 
3926
  print("🗄️ Creando tablas...")
3927
  try:
 
3937
 
3938
  print("\\n🎉 Proceso de población completado!")
3939
 
3940
+ # ✅ NUEVO: GENERAR BACKUP COMPLETO DESPUÉS DE POBLAR TODOS LOS MÓDULOS
3941
+ print("\\n💾 Generando backups JSON completos...")
3942
+ try:
3943
+ from utils.backup_manager import backup_manager
3944
+
3945
+ # Crear diccionario de modelos para backup
3946
+ models_dict = {{}}
3947
+ for module_name in {module_names}:
3948
+ try:
3949
+ model_class = getattr(models, module_name.capitalize())
3950
+ models_dict[module_name] = model_class
3951
+ except AttributeError:
3952
+ print(f" ⚠️ No se pudo encontrar modelo para: {{module_name}}")
3953
+
3954
+ if models_dict:
3955
+ backup_results = backup_manager.export_all_entities(db, models_dict)
3956
+ successful_backups = sum(backup_results.values())
3957
+ total_backups = len(backup_results)
3958
+ print(f" 📊 Backups generados: {{successful_backups}}/{{total_backups}} entidades")
3959
+
3960
+ # Mostrar resumen de backups
3961
+ backup_status = backup_manager.get_backup_status()
3962
+ print(f" 📁 Directorio de backups: {{backup_status['summary']['backup_directory']}}")
3963
+ print(f" 💽 Tamaño total: {{backup_status['summary']['total_size_kb']}} KB")
3964
+ else:
3965
+ print(" ⚠️ No se pudieron generar backups - sin modelos encontrados")
3966
+
3967
+ except Exception as backup_error:
3968
+ print(f" ❌ Error en sistema de backups: {{backup_error}}")
3969
+ import traceback
3970
+ traceback.print_exc()
3971
+
3972
  print("\\n📊 RESUMEN FINAL:")
3973
+ print("=" * 60)
3974
 
3975
  total_records = 0
3976
  for module_name in {module_names}:
 
3984
  except Exception as e:
3985
  print(f" ❌ {{module_name.capitalize():.<15}} Error: {{e}}")
3986
 
3987
+ print("=" * 60)
3988
+ print(f" 📈 TOTAL REGISTROS: {{total_records:>18}}")
3989
+ print(f" 💾 BACKUPS JSON: {'✅ ACTIVOS':>24}")
3990
+ print(f" 📁 DIRECTORIO: {'backups/json/':>24}")
3991
 
3992
  # ✅ VERIFICACIÓN DE CAMPOS FINANCIEROS EN MÓDULOS CLAVE
3993
  print("\\n💰 VERIFICACIÓN DE CAMPOS FINANCIEROS:")
 
4031
  except Exception as e:
4032
  print(f" ℹ️ No se pudieron verificar usuarios del sistema: {{e}}")
4033
 
4034
+ # ✅ NUEVO: INFORMACIÓN SOBRE BACKUPS
4035
+ print("\\n🔗 ACCESO A BACKUPS:")
4036
+ print(" 🌐 Ver en navegador: http://localhost:8000/backups/")
4037
+ print(" 📊 Estado de backups: http://localhost:8000/api/v1/backups/status")
4038
+ print(" 💾 Descargar backups: http://localhost:8000/api/v1/backups/download/{{entidad}}")
4039
+
4040
  except Exception as e:
4041
  print(f"💥 Error general en población: {{str(e)}}")
4042
  db.rollback()
 
6351
 
6352
  # Reemplazar la función generate_readme original
6353
  def generate_readme(**kwargs):
6354
+ return generate_complete_readme(**kwargs)