diff --git a/backend/api/v1/modules/core/auth/routes.py b/backend/api/v1/modules/core/auth/routes.py index 3dfe7eb..e5ee398 100644 --- a/backend/api/v1/modules/core/auth/routes.py +++ b/backend/api/v1/modules/core/auth/routes.py @@ -443,14 +443,21 @@ async def get_my_companies( tenant_id = resolve_effective_tenant_id_from_user(current_user) # 1) Usuario CON tenant en el token (flujo normal): autocrea una compañía por - # defecto en el primer acceso y asegura la membresía. + # defecto en el primer acceso y AUTO-LIGA al usuario a TODAS las compañías de + # su tenant. Así cualquier usuario del mismo tenant (misma organización del + # Workspace) entra y ve la(s) compañía(s) sin gestión manual. El ROL no se + # asigna aquí: es solo membresía; los permisos se otorgan aparte (un admin + # asigna el rol; el primer usuario recibe super_admin vía /permissions/me). if tenant_id: tenant_id = int(tenant_id) - exists = db.execute( - text("SELECT id FROM a76.company WHERE tenant_id = :tid ORDER BY id LIMIT 1"), - {"tid": tenant_id}, - ).fetchone() - if not exists: + company_ids = [ + int(r[0]) + for r in db.execute( + text("SELECT id FROM a76.company WHERE tenant_id = :tid ORDER BY id"), + {"tid": tenant_id}, + ).fetchall() + ] + if not company_ids: tenant = db.query(Tenant).filter(Tenant.id == tenant_id).first() default_name = ( (tenant.name if tenant else None) @@ -463,12 +470,16 @@ async def get_my_companies( ).fetchone() db.execute(text("SELECT setval('a76.company_id_seq', (SELECT MAX(id) FROM a76.company))")) db.commit() + company_ids = [int(created[0])] logger.info("Compañía por defecto creada para tenant=%s: id=%s", tenant_id, created[0]) - if user_id: + + # Auto-ligado por tenant (solo membresía, sin rol). + if user_id: + for cid in company_ids: try: - _ensure_user_tenant_for_company(db, str(user_id), tenant_id, int(created[0])) + _ensure_user_tenant_for_company(db, str(user_id), tenant_id, cid) except Exception as exc: - logger.warning("no se pudo asegurar user_tenant (no bloquea): %s", exc) + logger.warning("auto-ligado de compañía %s falló (no bloquea): %s", cid, exc) # 2) Compañías por MEMBRESÍA (user_tenants ∪ user_company_roles) → funciona # también para hub_admin sin tenant en el token: verá las compañías que creó