Files
soft_usite/rest/controllers/umind_oauth_controller.go
T
Lizandro GuarnizoandClaude Sonnet 5 f3f2f421d6 feat: uMind pasa a multi-agente por tenant
Un tenant (negocio/sitio, dueño de los dominios permitidos) puede tener
varios UmindAgente independientes (ej. "Ventas", "Soporte"), cada uno con
su propia config de IA, tono, base de conocimiento, tools, canales y
conexión de correo. El site_key también pasa a ser por agente, así cada
uno tiene su propio <script> de widget embebible y su propio color.

Backend:
- Nuevo modelo UmindAgente (pkg/models/umind_agente.go), con SiteKey,
  AiConfigID, Tono, MensajeBienvenida y Color — campos que antes vivían en
  UmindTenant y se sacan de ahí (las columnas viejas quedan huérfanas sin
  usar, no se hace DROP COLUMN).
- UmindDocumento, UmindChunk, UmindHerramienta, UmindCanal, UmindConexion y
  UmindMensaje pasan de TenantID a AgenteID. El campo se agrega sin
  "not null" para no romper el ALTER TABLE en Postgres sobre tablas que ya
  tienen filas (ej. emetropolitana).
- migrations.MigrarUmindAgentes(): idempotente, crea un agente "Principal"
  por cada tenant existente heredando lo que ya tenía configurado, y mueve
  sus datos de tenant_id a agente_id. Corre en cada arranque normal, mismo
  criterio que los Seed* — nada se rompe para los tenants ya en producción.
- Motor del agente, widget, canales (Telegram/WhatsApp) y OAuth de correo
  ahora operan sobre UmindAgente; el tenant solo se consulta para el
  chequeo de dominio permitido y el nombre del negocio que ve el visitante.

Frontend: nueva jerarquía de navegación tenant → lista de agentes
(TenantAgentes.vue) → detalle de un agente (AgenteDetail.vue, antes
TenantDetail.vue) con las mismas 6 tabs de siempre, ahora por agente. El
modal de tenant en el sidebar se achica a nombre/dominios/activo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-13 09:30:06 -05:00

89 lines
3.3 KiB
Go

package controllers
import (
"fmt"
"log"
"strconv"
"github.com/gofiber/fiber/v2"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
"github.com/sujit-baniya/fiber-boilerplate/pkg/services"
)
// GetUmindConexionesHandler lista las cuentas de correo conectadas de un
// agente, sin exponer los tokens (ni cifrados ni en claro).
func GetUmindConexionesHandler(c *fiber.Ctx) error {
agenteID, err := strconv.ParseUint(c.Query("agente_id"), 10, 64)
if err != nil || agenteID == 0 {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "agente_id requerido"})
}
items, err := models.GetUmindConexionesByAgente(uint(agenteID))
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
}
out := make([]fiber.Map, len(items))
for i, cx := range items {
out[i] = fiber.Map{
"ID": cx.ID, "agente_id": cx.AgenteID, "proveedor": cx.Proveedor,
"email": cx.Email, "activo": cx.Activo, "expira_en": cx.ExpiraEn,
}
}
return c.JSON(fiber.Map{"items": out})
}
// UmindConectarHandler redirige al staff a la pantalla de consentimiento de
// Google/Microsoft. Ruta: GET /app/umind/conexiones/conectar?agente_id=&proveedor=
func UmindConectarHandler(c *fiber.Ctx) error {
agenteID, err := strconv.ParseUint(c.Query("agente_id"), 10, 64)
if err != nil || agenteID == 0 {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "agente_id requerido"})
}
proveedor := c.Query("proveedor")
if _, err := models.GetUmindAgenteByID(uint(agenteID)); err != nil {
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"error": "agente no encontrado"})
}
url, err := services.IniciarConexionOAuth(proveedor, uint(agenteID))
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": err.Error()})
}
return c.Redirect(url, fiber.StatusFound)
}
// UmindOAuthCallbackHandler recibe la vuelta de Google/Microsoft, intercambia
// el code y redirige al staff de vuelta a la SPA.
// Ruta: GET /app/umind/conexiones/callback/:proveedor
func UmindOAuthCallbackHandler(c *fiber.Ctx) error {
proveedor := c.Params("proveedor")
if errParam := c.Query("error"); errParam != "" {
return c.Redirect(fmt.Sprintf("/orchestrator/?oauth_error=%s", errParam), fiber.StatusFound)
}
code := c.Query("code")
state := c.Query("state")
if code == "" || state == "" {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "callback inválido"})
}
conexion, err := services.CompletarConexionOAuth(proveedor, code, state)
if err != nil {
log.Printf("[UMIND_OAUTH] error completando conexión (%s): %v", proveedor, err)
return c.Redirect("/orchestrator/?oauth_error=1", fiber.StatusFound)
}
agente, err := models.GetUmindAgenteByID(conexion.AgenteID)
if err != nil {
return c.Redirect("/orchestrator/?oauth_error=1", fiber.StatusFound)
}
return c.Redirect(fmt.Sprintf("/orchestrator/tenants/%d/agentes/%d?tab=conexiones", agente.TenantID, agente.ID), fiber.StatusFound)
}
func DeleteUmindConexionHandler(c *fiber.Ctx) error {
id, err := strconv.ParseUint(c.Params("id"), 10, 64)
if err != nil {
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"error": "id inválido"})
}
if err := models.DeleteUmindConexion(uint(id)); err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"error": err.Error()})
}
return c.JSON(fiber.Map{"ok": true})
}