- Implemented SvelteKit frontend with authentication callback handling. - Created demo routes and paraglide localization functionality. - Added health check and entrypoint scripts for backend services. - Established PostgreSQL and Keycloak initialization scripts with health checks. - Introduced models for database schema using SQLAlchemy. - Configured Vite and SvelteKit for development and testing environments. - Added health check script to verify service statuses and resource usage. - Created Docker entrypoint scripts for seamless service startup.
112 lines
3.5 KiB
Python
112 lines
3.5 KiB
Python
"""
|
|
Script de inicialización de la base de datos
|
|
Crea las tablas y datos iniciales
|
|
"""
|
|
import sys
|
|
import os
|
|
|
|
# Agregar el directorio backend al path
|
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
from core.database import init_db, CoreSessionLocal
|
|
from api.v1.modules.a76.tenants.models import Tenant, TenantType
|
|
from api.v1.modules.a76.licenses.models import License, LicensePlan, LicenseStatus
|
|
from datetime import datetime, timedelta
|
|
import logging
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def create_initial_data():
|
|
"""Crea datos iniciales de prueba"""
|
|
db = CoreSessionLocal()
|
|
|
|
try:
|
|
# Verificar si ya existen datos
|
|
existing_tenant = db.query(Tenant).first()
|
|
if existing_tenant:
|
|
logger.info("Los datos iniciales ya existen. Saltando creación.")
|
|
return
|
|
|
|
logger.info("Creando tenant de prueba...")
|
|
|
|
# Crear tenant de prueba
|
|
tenant = Tenant(
|
|
name="Empresa Demo S.A. de C.V.",
|
|
slug="empresa-demo",
|
|
keycloak_realm="master", # Usar realm master para pruebas
|
|
type=TenantType.SHARED,
|
|
contact_name="Administrador Demo",
|
|
contact_email="admin@empresa-demo.com",
|
|
contact_phone="+52 55 1234 5678",
|
|
is_active=True
|
|
)
|
|
|
|
db.add(tenant)
|
|
db.commit()
|
|
db.refresh(tenant)
|
|
|
|
logger.info(f"Tenant creado: ID={tenant.id}, slug={tenant.slug}")
|
|
|
|
# Crear licencia para el tenant
|
|
logger.info("Creando licencia de prueba...")
|
|
|
|
license = License(
|
|
tenant_id=tenant.id,
|
|
plan=LicensePlan.PROFESSIONAL,
|
|
status=LicenseStatus.ACTIVE,
|
|
max_users=50,
|
|
max_storage_gb=100,
|
|
max_monthly_operations=25000,
|
|
feature_api_access=True,
|
|
feature_advanced_reports=True,
|
|
feature_integrations=True,
|
|
feature_dedicated_support=False,
|
|
starts_at=datetime.utcnow(),
|
|
expires_at=datetime.utcnow() + timedelta(days=365)
|
|
)
|
|
|
|
db.add(license)
|
|
db.commit()
|
|
|
|
logger.info(f"Licencia creada: Plan={license.plan.value}, Expira={license.expires_at}")
|
|
logger.info("✅ Datos iniciales creados exitosamente")
|
|
|
|
logger.info("\n" + "="*60)
|
|
logger.info("INFORMACIÓN IMPORTANTE PARA KEYCLOAK")
|
|
logger.info("="*60)
|
|
logger.info(f"Tenant Slug: {tenant.slug}")
|
|
logger.info(f"Tenant ID: {tenant.id}")
|
|
logger.info(f"Keycloak Realm: {tenant.keycloak_realm}")
|
|
logger.info("\nPara probar el login, necesitas:")
|
|
logger.info("1. Crear un usuario en Keycloak (realm: master)")
|
|
logger.info("2. Agregar el atributo 'tenant_id' con valor: 1")
|
|
logger.info("3. Asignar roles apropiados (user, admin, etc.)")
|
|
logger.info("="*60 + "\n")
|
|
|
|
except Exception as e:
|
|
db.rollback()
|
|
logger.error(f"Error creando datos iniciales: {str(e)}")
|
|
raise
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
logger.info("Inicializando base de datos...")
|
|
|
|
try:
|
|
# Crear tablas
|
|
init_db()
|
|
logger.info("✅ Tablas creadas exitosamente")
|
|
|
|
# Crear datos iniciales
|
|
create_initial_data()
|
|
|
|
logger.info("\n🎉 Base de datos inicializada correctamente")
|
|
|
|
except Exception as e:
|
|
logger.error(f"❌ Error inicializando base de datos: {str(e)}")
|
|
sys.exit(1)
|