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>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
8eba3ab97f
commit
f3f2f421d6
+30
-50
@@ -11,29 +11,25 @@ import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// UmindTenant representa un sitio/cliente que tiene el widget de uMind
|
||||
// instalado. SiteKey es pública (va en el <script> embebido del sitio,
|
||||
// cualquiera que vea el código fuente la puede ver) — la seguridad no
|
||||
// depende de que sea secreta, sino de que la petición venga de uno de los
|
||||
// DominiosPermitidos (igual que una site key de reCAPTCHA o Analytics).
|
||||
// UmindTenant representa un sitio/cliente de uMind — dueño de los dominios
|
||||
// permitidos y el nombre del negocio que se muestra al visitante. Un tenant
|
||||
// puede tener varios UmindAgente independientes (cada uno con su propia
|
||||
// config de IA, base de conocimiento, tools y canales); lo que antes vivía
|
||||
// acá (SiteKey, AiConfigID, Tono, MensajeBienvenida, Color) se movió a
|
||||
// UmindAgente — ver pkg/models/umind_agente.go y migrations.MigrarUmindAgentes.
|
||||
type UmindTenant struct {
|
||||
gorm.Model
|
||||
Nombre string `json:"nombre" gorm:"column:nombre;size:150;not null"`
|
||||
SiteKey string `json:"site_key" gorm:"column:site_key;uniqueIndex;size:40;not null"`
|
||||
DominiosPermitidos string `json:"dominios_permitidos" gorm:"column:dominios_permitidos;type:text"` // coma-separado, ej: u-site.app,www.u-site.app
|
||||
AiConfigID *uint `json:"ai_config_id" gorm:"column:ai_config_id"`
|
||||
Tono string `json:"tono" gorm:"column:tono;type:text"` // instrucciones de personalidad/tono, se inyectan al system prompt
|
||||
MensajeBienvenida string `json:"mensaje_bienvenida" gorm:"column:mensaje_bienvenida;type:text"`
|
||||
Color string `json:"color" gorm:"column:color;size:7;default:'#8eb02f'"` // hex, ej: #8eb02f — color de marca del widget embebido
|
||||
Activo bool `json:"activo" gorm:"column:activo;default:true"`
|
||||
CreadoPorID uint `json:"creado_por_id" gorm:"column:creado_por_id"`
|
||||
}
|
||||
|
||||
func (UmindTenant) TableName() string { return "umind_tenants" }
|
||||
|
||||
// GenerarSiteKey crea un identificador público único para el widget. No se
|
||||
// hashea (a diferencia de un token de API) porque no es un secreto: viaja en
|
||||
// el HTML público del sitio del cliente.
|
||||
// GenerarSiteKey crea un identificador público único para el widget de un
|
||||
// agente. No se hashea (a diferencia de un token de API) porque no es un
|
||||
// secreto: viaja en el HTML público del sitio del cliente.
|
||||
func GenerarSiteKey() (string, error) {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
@@ -43,13 +39,6 @@ func GenerarSiteKey() (string, error) {
|
||||
}
|
||||
|
||||
func CreateUmindTenant(t *UmindTenant) error {
|
||||
if t.SiteKey == "" {
|
||||
key, err := GenerarSiteKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t.SiteKey = key
|
||||
}
|
||||
return app.Http.Database.DB.Create(t).Error
|
||||
}
|
||||
|
||||
@@ -74,16 +63,6 @@ func GetUmindTenantByID(id uint) (*UmindTenant, error) {
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// GetUmindTenantBySiteKey resuelve el tenant a partir de la site_key pública
|
||||
// que manda el widget. Solo hace match si el tenant está activo.
|
||||
func GetUmindTenantBySiteKey(siteKey string) (*UmindTenant, error) {
|
||||
var t UmindTenant
|
||||
if err := app.Http.Database.DB.Where("site_key = ? AND activo = ?", siteKey, true).First(&t).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
func UpdateUmindTenant(id uint, updates map[string]interface{}) error {
|
||||
return app.Http.Database.DB.Model(&UmindTenant{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
@@ -126,11 +105,12 @@ func (t *UmindTenant) DominioPermitido(host string) bool {
|
||||
|
||||
// ─── Documentos y chunks de conocimiento ────────────────────────────────────
|
||||
|
||||
// UmindDocumento es una fuente de conocimiento del tenant: una URL crawleada
|
||||
// o un archivo subido. Se trocea en UmindChunk para la búsqueda por similitud.
|
||||
// UmindDocumento es una fuente de conocimiento de un agente: una URL
|
||||
// crawleada o un archivo subido. Se trocea en UmindChunk para la búsqueda
|
||||
// por similitud.
|
||||
type UmindDocumento struct {
|
||||
gorm.Model
|
||||
TenantID uint `json:"tenant_id" gorm:"column:tenant_id;index;not null"`
|
||||
AgenteID uint `json:"agente_id" gorm:"column:agente_id;index"`
|
||||
Tipo string `json:"tipo" gorm:"column:tipo;size:20"` // url | archivo
|
||||
Origen string `json:"origen" gorm:"column:origen;type:text"` // la URL crawleada, o el nombre del archivo
|
||||
Estado string `json:"estado" gorm:"column:estado;default:'pendiente'"` // pendiente | procesando | listo | error
|
||||
@@ -144,9 +124,9 @@ func CreateUmindDocumento(d *UmindDocumento) error {
|
||||
return app.Http.Database.DB.Create(d).Error
|
||||
}
|
||||
|
||||
func GetUmindDocumentosByTenant(tenantID uint) ([]UmindDocumento, error) {
|
||||
func GetUmindDocumentosByAgente(agenteID uint) ([]UmindDocumento, error) {
|
||||
var items []UmindDocumento
|
||||
err := app.Http.Database.DB.Where("tenant_id = ?", tenantID).Order("id DESC").Find(&items).Error
|
||||
err := app.Http.Database.DB.Where("agente_id = ?", agenteID).Order("id DESC").Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
@@ -176,11 +156,11 @@ func DeleteUmindDocumento(id uint) error {
|
||||
// UmindChunk es un fragmento de texto con su embedding, listo para búsqueda
|
||||
// por similitud. Sin pgvector por ahora: el embedding se guarda como JSON de
|
||||
// []float32 y la similitud se calcula en memoria (suficiente para el volumen
|
||||
// de un piloto de un solo tenant; si el volumen crece, se migra a pgvector
|
||||
// de un piloto de un solo agente; si el volumen crece, se migra a pgvector
|
||||
// sin cambiar la interfaz de búsqueda).
|
||||
type UmindChunk struct {
|
||||
gorm.Model
|
||||
TenantID uint `json:"tenant_id" gorm:"column:tenant_id;index;not null"`
|
||||
AgenteID uint `json:"agente_id" gorm:"column:agente_id;index"`
|
||||
DocumentoID uint `json:"documento_id" gorm:"column:documento_id;index;not null"`
|
||||
Contenido string `json:"contenido" gorm:"column:contenido;type:text;not null"`
|
||||
EmbeddingJSON string `json:"-" gorm:"column:embedding_json;type:text"`
|
||||
@@ -213,21 +193,21 @@ func CreateUmindChunks(chunks []UmindChunk) error {
|
||||
return app.Http.Database.DB.CreateInBatches(chunks, 50).Error
|
||||
}
|
||||
|
||||
// GetUmindChunksByTenant retorna todos los chunks del tenant, para la
|
||||
// GetUmindChunksByAgente retorna todos los chunks del agente, para la
|
||||
// búsqueda por similitud en memoria.
|
||||
func GetUmindChunksByTenant(tenantID uint) ([]UmindChunk, error) {
|
||||
func GetUmindChunksByAgente(agenteID uint) ([]UmindChunk, error) {
|
||||
var items []UmindChunk
|
||||
err := app.Http.Database.DB.Where("tenant_id = ?", tenantID).Find(&items).Error
|
||||
err := app.Http.Database.DB.Where("agente_id = ?", agenteID).Find(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
// ─── Historial de conversación del widget ───────────────────────────────────
|
||||
|
||||
// UmindMensaje guarda el historial de conversación del widget, por tenant y
|
||||
// UmindMensaje guarda el historial de conversación del widget, por agente y
|
||||
// sesión de navegador (no hay usuario autenticado del lado del visitante).
|
||||
type UmindMensaje struct {
|
||||
gorm.Model
|
||||
TenantID uint `json:"tenant_id" gorm:"column:tenant_id;index;not null"`
|
||||
AgenteID uint `json:"agente_id" gorm:"column:agente_id;index"`
|
||||
SessionID string `json:"session_id" gorm:"column:session_id;index;not null"`
|
||||
Role string `json:"role" gorm:"column:role;not null"` // user | assistant
|
||||
Content string `json:"content" gorm:"column:content;type:text;not null"`
|
||||
@@ -235,16 +215,16 @@ type UmindMensaje struct {
|
||||
|
||||
func (UmindMensaje) TableName() string { return "umind_mensajes" }
|
||||
|
||||
func SaveUmindMensaje(tenantID uint, sessionID, role, content string) error {
|
||||
m := &UmindMensaje{TenantID: tenantID, SessionID: sessionID, Role: role, Content: content}
|
||||
func SaveUmindMensaje(agenteID uint, sessionID, role, content string) error {
|
||||
m := &UmindMensaje{AgenteID: agenteID, SessionID: sessionID, Role: role, Content: content}
|
||||
return app.Http.Database.DB.Create(m).Error
|
||||
}
|
||||
|
||||
// GetUmindHistorial retorna los últimos n mensajes de una sesión, en orden cronológico.
|
||||
func GetUmindHistorial(tenantID uint, sessionID string, n int) ([]UmindMensaje, error) {
|
||||
func GetUmindHistorial(agenteID uint, sessionID string, n int) ([]UmindMensaje, error) {
|
||||
var items []UmindMensaje
|
||||
err := app.Http.Database.DB.
|
||||
Where("tenant_id = ? AND session_id = ?", tenantID, sessionID).
|
||||
Where("agente_id = ? AND session_id = ?", agenteID, sessionID).
|
||||
Order("created_at DESC").
|
||||
Limit(n).
|
||||
Find(&items).Error
|
||||
@@ -254,19 +234,19 @@ func GetUmindHistorial(tenantID uint, sessionID string, n int) ([]UmindMensaje,
|
||||
return items, err
|
||||
}
|
||||
|
||||
// GetUmindSesiones lista las sesiones de conversación recientes de un tenant
|
||||
// GetUmindSesiones lista las sesiones de conversación recientes de un agente
|
||||
// (para el panel admin), con el último mensaje como resumen.
|
||||
func GetUmindSesiones(tenantID uint, limit int) ([]UmindMensaje, error) {
|
||||
func GetUmindSesiones(agenteID uint, limit int) ([]UmindMensaje, error) {
|
||||
var items []UmindMensaje
|
||||
err := app.Http.Database.DB.Raw(`
|
||||
SELECT * FROM (
|
||||
SELECT DISTINCT ON (session_id) *
|
||||
FROM umind_mensajes
|
||||
WHERE tenant_id = ? AND deleted_at IS NULL
|
||||
WHERE agente_id = ? AND deleted_at IS NULL
|
||||
ORDER BY session_id, created_at DESC
|
||||
) ultimos
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ?
|
||||
`, tenantID, limit).Scan(&items).Error
|
||||
`, agenteID, limit).Scan(&items).Error
|
||||
return items, err
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user