feat: pantalla para administrar chats autorizados del agente de Telegram

Antes la whitelist de telegram_agent_auth solo se podía tocar con curl/Postman
contra /api/v2/agent/auth. Se agrega /app/agente/chats-autorizados con un
CRUD simple, más un botón "buscar mensajes recientes" (UpdatesRecientesDelBot,
vía getUpdates) para descubrir el chat_id de alguien que le acaba de escribir
al bot sin tener que pedírselo por otro medio. Entrada nueva en el menú lateral
del módulo Automatización IA.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Lizandro GD
2026-08-03 02:37:40 +00:00
co-authored by Claude Sonnet 5
parent 7b0e4b9b5c
commit 5607836261
6 changed files with 311 additions and 0 deletions
+1
View File
@@ -441,6 +441,7 @@ func SeedAutomatizacionIA() {
// 2. Definir submódulos
entries := []struct{ title, desc, url string }{
{"Asistente", "Chat propio: mismo motor y tools que el bot de Telegram", "/app/asistente"},
{"Chats autorizados", "Quién puede hablarle al bot de Telegram y ejecutar acciones", "/app/agente/chats-autorizados"},
{"Plantillas de Documento", "Fuente de verdad de cotización, contrato, acta y cuenta de cobro", "/app/automatizacion/plantillas"},
{"Tarifas", "Valor por hora, licencias, VMs y márgenes usados al cotizar", "/app/automatizacion/tarifas"},
}
+62
View File
@@ -84,3 +84,65 @@ func (ts *TelegramService) SendMessageWithToken(chatID interface{}, message, bot
svc := &TelegramService{BotToken: botToken}
return svc.SendMessage(chatID, message)
}
// RemitenteReciente es alguien que le escribió al bot recientemente, útil para
// descubrir su chat_id sin tener que pedírselo por otro medio.
type RemitenteReciente struct {
ChatID int64
Nombre string
Mensaje string
}
// UpdatesRecientesDelBot consulta getUpdates y devuelve, más reciente primero,
// los remitentes que le han escrito al bot (hasta los últimos 100 updates que
// Telegram todavía tenga en cola).
func UpdatesRecientesDelBot(botToken string) ([]RemitenteReciente, error) {
if botToken == "" {
return nil, fmt.Errorf("bot token vacío")
}
resp, err := http.Get(fmt.Sprintf("https://api.telegram.org/bot%s/getUpdates?limit=100", botToken)) //nolint:noctx
if err != nil {
return nil, fmt.Errorf("no se pudo consultar Telegram: %w", err)
}
defer resp.Body.Close()
var result struct {
OK bool `json:"ok"`
Result []struct {
Message struct {
From struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Username string `json:"username"`
} `json:"from"`
Chat struct {
ID int64 `json:"id"`
} `json:"chat"`
Text string `json:"text"`
} `json:"message"`
} `json:"result"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil || !result.OK {
return nil, fmt.Errorf("Telegram no devolvió updates válidos")
}
out := make([]RemitenteReciente, 0, len(result.Result))
for i := len(result.Result) - 1; i >= 0; i-- {
m := result.Result[i].Message
if m.Chat.ID == 0 {
continue
}
nombre := m.From.FirstName
if m.From.LastName != "" {
nombre += " " + m.From.LastName
}
if m.From.Username != "" {
nombre += " (@" + m.From.Username + ")"
}
if nombre == "" {
nombre = fmt.Sprintf("Chat %d", m.Chat.ID)
}
out = append(out, RemitenteReciente{ChatID: m.Chat.ID, Nombre: nombre, Mensaje: m.Text})
}
return out, nil
}
@@ -0,0 +1,195 @@
<div x-data="app" class="bg-white rounded-lg shadow">
<div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex justify-center items-center z-50">
<img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
</div>
<div class="container mx-auto p-6 w-full">
<div class="justify-between items-center w-full md:flex mb-4">
<div>
<h1 class="text-2xl font-bold mb-1">Chats autorizados del agente</h1>
<p class="text-sm text-gray-500">Quién puede hablarle al bot de Telegram y pedirle acciones (crear cotizaciones, deploys, contabilidad, etc.)</p>
</div>
<button @click="addModal = true" class="bg-[#8eb02f] text-white px-4 py-2 rounded text-sm mt-3 md:mt-0">+ Autorizar chat</button>
</div>
<div class="mb-4 p-3 bg-blue-50 rounded text-xs text-blue-700 leading-6">
Cualquiera puede encontrar y escribirle al bot en Telegram, pero solo los chats de esta lista reciben respuesta y pueden ejecutar acciones. Si la lista está vacía, solo responde al chat configurado en <code>/app/telegram</code>.
</div>
<div class="overflow-x-auto">
<table class="table-auto w-full text-sm">
<thead class="text-left border-b border-gray-200 bg-gray-50">
<tr>
<th class="py-2 px-3">Nombre</th>
<th class="py-2 px-3">Chat ID</th>
<th class="py-2 px-3">Estado</th>
<th class="py-2 px-3 w-20"></th>
</tr>
</thead>
<tbody class="text-gray-600">
<template x-for="d in datos" :key="d.ID">
<tr class="hover:bg-gray-50 border-b border-gray-100">
<td class="py-2 px-3 font-medium" x-text="d.nombre || '(sin nombre)'"></td>
<td class="py-2 px-3 font-mono text-xs" x-text="d.chat_id"></td>
<td class="py-2 px-3">
<span class="px-2 py-0.5 rounded text-xs font-medium"
:class="d.activo ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'"
x-text="d.activo ? 'Autorizado' : 'Inactivo'"></span>
</td>
<td class="py-2 px-3">
<button @click="openDelete(d)" title="Quitar acceso" class="text-gray-400 hover:text-red-500">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"/></svg>
</button>
</td>
</tr>
</template>
<tr x-show="!loading && datos.length===0">
<td colspan="4" class="text-center text-gray-400 py-8">Nadie autorizado todavía — el bot solo responde al chat configurado en /app/telegram</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Modal Autorizar -->
<div x-show="addModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div class="bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 p-6 max-h-[85vh] overflow-y-auto" @click.stop>
<h2 class="text-lg font-semibold mb-1">Autorizar chat</h2>
<p class="text-xs text-gray-500 mb-4">Pide a la persona que le escriba cualquier mensaje al bot en Telegram y luego busca su chat entre los mensajes recientes.</p>
<div class="mb-4">
<button @click="buscarRecientes()" :disabled="buscando" class="text-xs font-semibold px-3 py-1.5 rounded border border-[#8eb02f] text-[#8eb02f] hover:bg-[#8eb02f]/10 disabled:opacity-50">
<span x-show="!buscando">🔄 Buscar mensajes recientes</span>
<span x-show="buscando">Buscando…</span>
</button>
<div x-show="recientes.length > 0" class="mt-3 border rounded-lg divide-y max-h-48 overflow-y-auto">
<template x-for="r in recientes" :key="r.chat_id">
<button type="button" @click="elegirReciente(r)" class="w-full text-left px-3 py-2 text-xs hover:bg-gray-50 flex justify-between items-center">
<span>
<span class="font-medium text-gray-700" x-text="r.nombre"></span>
<span class="text-gray-400 block truncate" x-text="r.mensaje"></span>
</span>
<span class="text-gray-300 font-mono" x-text="r.chat_id"></span>
</button>
</template>
</div>
<p x-show="buscando === false && recientesBuscado && recientes.length === 0" class="text-xs text-gray-400 mt-2">No hay mensajes nuevos de nadie sin autorizar todavía.</p>
</div>
<form @submit.prevent="save()" class="space-y-3 border-t pt-4">
<div>
<label class="text-xs font-medium text-gray-600">Chat ID *</label>
<input x-model="form.chat_id" required type="text" inputmode="numeric" placeholder="Ej: 123456789"
class="mt-1 w-full border rounded px-3 py-2 text-sm font-mono" />
</div>
<div>
<label class="text-xs font-medium text-gray-600">Nombre</label>
<input x-model="form.nombre" class="mt-1 w-full border rounded px-3 py-2 text-sm" placeholder="Para identificarlo en la lista" />
</div>
<div class="flex justify-end gap-2 mt-5">
<button type="button" @click="closeModals()" class="px-4 py-2 border rounded text-sm">Cancelar</button>
<button type="submit" class="px-4 py-2 bg-[#8eb02f] text-white rounded text-sm" :disabled="loading">
<span x-text="loading ? 'Guardando…' : 'Autorizar'"></span>
</button>
</div>
</form>
</div>
</div>
<!-- Modal Quitar -->
<div x-show="deleteModal" x-cloak class="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div class="bg-white rounded-lg shadow-xl p-6 w-full max-w-sm mx-4 text-center" @click.stop>
<p class="font-semibold mb-1">¿Quitar el acceso de este chat?</p>
<p class="text-sm text-gray-400 mb-5">Dejará de poder usar al agente por Telegram.</p>
<div class="flex justify-center gap-3">
<button @click="closeModals()" class="px-4 py-2 border rounded text-sm">Cancelar</button>
<button @click="deleteItem()" class="px-4 py-2 bg-red-500 text-white rounded text-sm">Quitar</button>
</div>
</div>
</div>
<div x-show="toast.show" x-cloak x-transition
class="fixed bottom-4 right-4 z-[100] px-4 py-3 rounded shadow-lg text-sm text-white"
:class="toast.type==='error' ? 'bg-red-500' : 'bg-[#8eb02f]'"
x-text="toast.msg"></div>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('app', () => ({
loading: false,
datos: [],
addModal: false, deleteModal: false,
selectedId: null,
form: { chat_id: '', nombre: '' },
recientes: [], buscando: false, recientesBuscado: false,
toast: { show: false, msg: '', type: 'ok' },
async init() { await this.loadData(); },
async loadData() {
this.loading = true;
try {
const { data } = await axios.get('/app/api/agent/auth');
this.datos = data.items || [];
} catch (e) { this.showToast(e.response?.data?.error || 'Error al cargar', 'error'); }
this.loading = false;
},
async buscarRecientes() {
this.buscando = true;
this.recientesBuscado = false;
try {
const { data } = await axios.get('/app/api/agent/auth/recientes');
this.recientes = data.items || [];
} catch (e) {
this.showToast(e.response?.data?.error || 'No se pudo consultar Telegram', 'error');
}
this.buscando = false;
this.recientesBuscado = true;
},
elegirReciente(r) {
this.form.chat_id = String(r.chat_id);
this.form.nombre = r.nombre;
},
openDelete(d) { this.selectedId = d.ID; this.deleteModal = true; },
closeModals() {
this.addModal = this.deleteModal = false;
this.selectedId = null;
this.form = { chat_id: '', nombre: '' };
this.recientes = [];
this.recientesBuscado = false;
},
async save() {
this.loading = true;
try {
await axios.post('/app/api/agent/auth', { chat_id: Number(this.form.chat_id), nombre: this.form.nombre });
this.showToast('Chat autorizado');
this.closeModals();
await this.loadData();
} catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
this.loading = false;
},
async deleteItem() {
this.loading = true;
try {
await axios.delete(`/app/api/agent/auth/${this.selectedId}`);
this.showToast('Acceso quitado');
this.closeModals();
await this.loadData();
} catch (e) { this.showToast(e.response?.data?.error || 'Error', 'error'); }
this.loading = false;
},
showToast(msg, type = 'ok') {
this.toast = { show: true, msg, type };
setTimeout(() => this.toast.show = false, 3000);
}
}));
});
</script>
@@ -170,6 +170,51 @@ func sendAgentReply(botToken string, chatID int64, text string) error {
// ─── CRUD de chats autorizados ────────────────────────────────────────────────
// AgentAuthView renderiza la pantalla de administración de chats autorizados.
func AgentAuthView(c *fiber.Ctx) error {
return c.Render("automatizacion/chats_autorizados", fiber.Map{
"user": c.Locals("user"),
"modules": c.Locals("userModules"),
}, "layouts/main")
}
// AgentAuthRecientes consulta los últimos mensajes recibidos por el bot del
// agente (getUpdates) y devuelve los remitentes distintos que todavía no están
// autorizados, para que el admin pueda autorizarlos con un clic sin tener que
// buscar el chat_id a mano.
func AgentAuthRecientes(c *fiber.Ctx) error {
tgCfg, err := models.GetAgentTelegramConfig()
if err != nil || tgCfg.BotToken == "" {
return c.Status(400).JSON(fiber.Map{"error": "No hay un bot de Telegram configurado para el agente"})
}
autorizados, _ := models.GetAllAgentAuth()
yaAutorizado := map[int64]bool{}
for _, a := range autorizados {
yaAutorizado[a.ChatID] = true
}
remitentes, err := services.UpdatesRecientesDelBot(tgCfg.BotToken)
if err != nil {
return c.Status(502).JSON(fiber.Map{"error": err.Error()})
}
type item struct {
ChatID int64 `json:"chat_id"`
Nombre string `json:"nombre"`
Mensaje string `json:"mensaje"`
}
seen := map[int64]bool{}
out := make([]item, 0, len(remitentes))
for _, r := range remitentes {
if seen[r.ChatID] || yaAutorizado[r.ChatID] {
continue
}
seen[r.ChatID] = true
out = append(out, item{ChatID: r.ChatID, Nombre: r.Nombre, Mensaje: r.Mensaje})
}
return c.JSON(fiber.Map{"items": out})
}
func AgentAuthList(c *fiber.Ctx) error {
items, err := models.GetAllAgentAuth()
if err != nil {
+1
View File
@@ -401,6 +401,7 @@ func AdminApiRoutes(api fiber.Router) {
// ─── Agente Telegram: chats autorizados ──────────────────────────────────
h.Get("/agent/auth", controllers.AgentAuthList)
h.Get("/agent/auth/recientes", controllers.AgentAuthRecientes)
h.Post("/agent/auth", controllers.AgentAuthCreate)
h.Delete("/agent/auth/:id", controllers.AgentAuthDelete)
h.Delete("/agent/history/:chat_id", controllers.AgentHistoryClear)
+7
View File
@@ -76,6 +76,13 @@ func RenovacionesRoutes(protected fiber.Router) {
protected.Post("/api/asistente/chat", controllers.PostAsistenteChat)
protected.Delete("/api/asistente/historial", controllers.DeleteAsistenteHistorial)
// ─── Automatización IA: Chats autorizados del agente (Telegram) ────
protected.Get("/agente/chats-autorizados", middlewares.MenuMiddleware, controllers.AgentAuthView)
protected.Get("/api/agent/auth", controllers.AgentAuthList)
protected.Get("/api/agent/auth/recientes", controllers.AgentAuthRecientes)
protected.Post("/api/agent/auth", controllers.AgentAuthCreate)
protected.Delete("/api/agent/auth/:id", controllers.AgentAuthDelete)
// ─── Automatización IA: Plantillas de documento ────────────────────
protected.Get("/automatizacion/plantillas", middlewares.MenuMiddleware, controllers.PlantillasDocumentoView)
protected.Get("/api/plantillas-documento", controllers.GetPlantillasDocumento)