Files
botino/public/components/ops-shell.js
Lucas Tettamanti 6376739f48 Frontend: scroll fix, SSE reconnect, toast global, stale states, theming
5 bloques en una pasada:

A. Scroll fixes (síntoma reportado por el usuario):
   - run-timeline: nuevo flag _userScrolledUp con detección por rAF en
     bindScroll. Auto-scroll al final SOLO si el usuario está abajo
     (umbral 150px) o si él mismo disparó un optimistic bubble. Cuando
     el usuario manda mensaje, se resetea el flag y se scrollea.
   - conversation-inspector: mismo patrón. ui:chatScroll respeta el
     flag userScrolledUp del emisor para no perseguir al usuario que
     lee arriba.
   - .bubble: + min-width:0, overflow-wrap:anywhere para URLs/JSON
     largos sin espacios.
   - <pre>: + overflow-x:auto, max-width:100%.
   - chat-simulator: textarea con resize:vertical, min/max heights
     viewport-friendly. inputs-col con overflow-y:auto.

B. Stale state options:
   - conversation-list y conversations-crud: dropdowns ahora muestran
     IDLE / CART / SHIPPING / AWAITING_HUMAN. Quitados BROWSING,
     BUILDING_ORDER, WAITING_ADDRESS, WAITING_PAYMENT, COMPLETED.
   - main.js: simulated plan.next_state pasa a CART.

C. SSE resilience (lib/sse.js):
   - connect() con backoff exponencial (1s → 30s).
   - safeParse() helper: cada evento envuelve JSON.parse en try-catch
     para que un payload malformado no rompa otros listeners.
   - reset retryDelay al primer "hello" exitoso.
   - ops-shell: indicador con dot (verde "En vivo" / naranja pulsante
     "Reconectando…") en lugar de texto plano.

D. Toast service global (public/lib/toast.js):
   - API simple: toast({ kind, text, ms }). Apila, animación slide-in,
     auto-dismiss 4s. Click para cerrar.
   - safeFetch en api.js: wrapper que dispara toast en network error y
     non-OK. Migrados simEvolution + retryLast.
   - chat-simulator usa toast en lugar de status text efímero.

E. Theming con CSS vars:
   - public/styles/theme.css con paleta completa (panels, borders,
     text, accents, bubbles, charts, radii, shadows). Linkeado desde
     index.html.
   - Migrados a var(--*) los 5 componentes más visibles:
     run-timeline, chat-simulator, conversation-inspector,
     conversation-list, home-dashboard. Custom properties heredan a
     través del shadow DOM, así que los demás componentes pueden
     migrar gradualmente sin cambios estructurales.
   - home-dashboard ya tenía vars locales: ahora apuntan a las globales.

Backend: 192/192 tests pasando. Sin cambios de API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-02 03:25:03 -03:00

279 lines
11 KiB
JavaScript

import { emit, on } from "../lib/bus.js";
import { navigateToView, navigateToItem } from "../lib/router.js";
import { api } from "../lib/api.js";
class OpsShell extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this._currentView = "chat";
this._currentParams = {};
this._takeoverCount = 0;
this.shadowRoot.innerHTML = `
<style>
:host { --bg:#0b0f14; --panel:#121823; --muted:#8aa0b5; --text:#e7eef7; --line:#1e2a3a; --blue:#1f6feb; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.app { height:100vh; background:var(--bg); color:var(--text); display:flex; flex-direction:column; }
header { display:flex; gap:12px; align-items:center; padding:12px 16px; border-bottom:1px solid var(--line); flex-wrap:wrap; }
header h1 { font-size:14px; margin:0; color:var(--muted); font-weight:700; letter-spacing:.4px; text-transform:uppercase; }
.nav { display:flex; gap:4px; margin-left:24px; flex-wrap:wrap; }
.nav-btn { background:transparent; border:1px solid var(--line); color:var(--muted); padding:6px 12px; border-radius:6px; font-size:12px; cursor:pointer; transition:all .15s; text-decoration:none; }
.nav-btn:hover { border-color:var(--blue); color:var(--text); }
.nav-btn.active { background:var(--blue); border-color:var(--blue); color:#fff; }
.spacer { flex:1; }
.status { font-size:12px; color:var(--muted); display:flex; align-items:center; gap:6px; }
.status .dot { width:8px; height:8px; border-radius:50%; background:#25D366; }
.status.disconnected .dot { background:#F59E0B; animation: pulse 1.2s ease-in-out infinite; }
.status.disconnected { color:#F59E0B; }
@keyframes pulse { 0%,100% { opacity:1; } 50% { opacity:.35; } }
/* Notification bell */
.notification-bell { position:relative; cursor:pointer; padding:8px; margin-right:12px; }
.notification-bell svg { width:20px; height:20px; fill:var(--muted); transition:fill .15s; }
.notification-bell:hover svg { fill:var(--text); }
.notification-bell.has-pending svg { fill:#f39c12; }
.notification-bell .badge {
position:absolute; top:2px; right:2px;
background:#e74c3c; color:#fff;
font-size:10px; padding:2px 6px; border-radius:10px;
font-weight:700; min-width:18px; text-align:center;
}
/* Layout para chat activo (2 columnas: burbujas + inspector) */
.layout-chat { height:100%; display:grid; grid-template-columns:1fr 1fr; grid-template-rows:1fr 310px; min-height:0; overflow:hidden; }
.col { border-right:1px solid var(--line); min-height:0; overflow:hidden; }
.chatTop { grid-column:1; grid-row:1; border-bottom:1px solid var(--line); }
.chatBottom { grid-column:1 / 3; grid-row:2; overflow:hidden; border-top:1px solid var(--line); }
.inspectorTop { grid-column:2; grid-row:1; border-right:none; }
/* Layout para CRUDs */
.layout-crud { height:100%; display:block; min-height:0; overflow:hidden; }
.view { display:none; flex:1; min-height:0; overflow:hidden; }
.view.active { display:flex; flex-direction:column; }
</style>
<div class="app">
<header>
<h1>Bot Ops Console</h1>
<nav class="nav">
<a class="nav-btn active" href="/home" data-view="home">Home</a>
<a class="nav-btn" href="/chat" data-view="chat">Chat</a>
<a class="nav-btn" href="/conversaciones" data-view="conversations">Conversaciones</a>
<a class="nav-btn" href="/usuarios" data-view="users">Usuarios</a>
<a class="nav-btn" href="/productos" data-view="products">Productos</a>
<a class="nav-btn" href="/equivalencias" data-view="aliases">Equivalencias</a>
<a class="nav-btn" href="/crosssell" data-view="crosssell">Cross-sell</a>
<a class="nav-btn" href="/cantidades" data-view="quantities">Cantidades</a>
<a class="nav-btn" href="/pedidos" data-view="orders">Pedidos</a>
<a class="nav-btn" href="/config-prompts" data-view="prompts">Prompts</a>
<a class="nav-btn" href="/configuracion" data-view="settings">Config</a>
<a class="nav-btn" href="/test" data-view="test">Test</a>
</nav>
<div class="spacer"></div>
<div class="notification-bell" id="notificationBell" title="Takeovers pendientes">
<svg viewBox="0 0 24 24"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z"/></svg>
<span class="badge" id="takeoverBadge" style="display:none;">0</span>
</div>
<div class="status disconnected" id="sseStatus"><span class="dot"></span><span class="label">Conectando…</span></div>
</header>
<div id="viewHome" class="view active">
<div class="layout-crud">
<home-dashboard></home-dashboard>
</div>
</div>
<div id="viewChat" class="view">
<div class="layout-chat">
<div class="col chatTop"><run-timeline></run-timeline></div>
<div class="col inspectorTop"><conversation-inspector></conversation-inspector></div>
<div class="col chatBottom"><chat-simulator></chat-simulator></div>
</div>
</div>
<div id="viewConversations" class="view">
<div class="layout-crud">
<conversations-crud></conversations-crud>
</div>
</div>
<div id="viewUsers" class="view">
<div class="layout-crud">
<users-crud></users-crud>
</div>
</div>
<div id="viewProducts" class="view">
<div class="layout-crud">
<products-crud></products-crud>
</div>
</div>
<div id="viewAliases" class="view">
<div class="layout-crud">
<aliases-crud></aliases-crud>
</div>
</div>
<div id="viewCrosssell" class="view">
<div class="layout-crud">
<recommendations-crud rule-type="crosssell"></recommendations-crud>
</div>
</div>
<div id="viewQuantities" class="view">
<div class="layout-crud">
<quantities-crud></quantities-crud>
</div>
</div>
<div id="viewOrders" class="view">
<div class="layout-crud">
<orders-crud></orders-crud>
</div>
</div>
<div id="viewTest" class="view">
<div class="layout-crud">
<test-panel></test-panel>
</div>
</div>
<div id="viewPrompts" class="view">
<div class="layout-crud">
<prompts-crud></prompts-crud>
</div>
</div>
<div id="viewTakeovers" class="view">
<div class="layout-crud">
<takeovers-crud></takeovers-crud>
</div>
</div>
<div id="viewSettings" class="view">
<div class="layout-crud">
<settings-crud></settings-crud>
</div>
</div>
</div>
`;
}
connectedCallback() {
this._unsub = on("sse:status", (s) => {
const el = this.shadowRoot.getElementById("sseStatus");
if (!el) return;
el.classList.toggle("disconnected", !s.ok);
const label = el.querySelector(".label");
if (label) label.textContent = s.ok ? "En vivo" : "Reconectando…";
});
// Listen for view switch requests from other components
this._unsubSwitch = on("ui:switchView", ({ view }) => {
if (view) this.setView(view, {}, { updateUrl: true });
});
// Listen for router changes (popstate, initial load)
this._unsubRouter = on("router:change", ({ view, params }) => {
this.setView(view, params, { updateUrl: false });
});
// Navigation - intercept clicks on nav links
const navBtns = this.shadowRoot.querySelectorAll(".nav-btn");
for (const btn of navBtns) {
btn.onclick = (e) => {
e.preventDefault();
const view = btn.dataset.view;
this.setView(view, {}, { updateUrl: true });
};
}
// Notification bell click
const bell = this.shadowRoot.getElementById("notificationBell");
bell.onclick = () => {
this.setView("takeovers", {}, { updateUrl: true });
};
// Listen for new takeovers via SSE - update badge immediately
this._unsubTakeover = on("takeover:created", () => {
this._takeoverCount++;
this.updateTakeoverBadge(this._takeoverCount);
});
// Start polling for takeovers
this.pollTakeovers();
this._pollInterval = setInterval(() => this.pollTakeovers(), 30000);
}
disconnectedCallback() {
this._unsub?.();
this._unsubSwitch?.();
this._unsubRouter?.();
this._unsubTakeover?.();
if (this._pollInterval) clearInterval(this._pollInterval);
}
async pollTakeovers() {
try {
const data = await api.takeovers({ limit: 1 });
const count = data.pending_count || (data.items?.length || 0);
this._takeoverCount = count;
this.updateTakeoverBadge(count);
} catch (e) {
// Silently fail - don't break the UI
console.debug("Error polling takeovers:", e);
}
}
updateTakeoverBadge(count) {
const badge = this.shadowRoot.getElementById("takeoverBadge");
const bell = this.shadowRoot.getElementById("notificationBell");
if (count > 0) {
badge.textContent = count > 99 ? "99+" : count;
badge.style.display = "inline";
bell.classList.add("has-pending");
bell.title = `${count} takeover(s) pendiente(s)`;
} else {
badge.style.display = "none";
bell.classList.remove("has-pending");
bell.title = "No hay takeovers pendientes";
}
}
setView(viewName, params = {}, { updateUrl = true } = {}) {
this._currentView = viewName;
this._currentParams = params;
// Update nav buttons
const navBtns = this.shadowRoot.querySelectorAll(".nav-btn");
for (const btn of navBtns) {
btn.classList.toggle("active", btn.dataset.view === viewName);
}
// Update views
const views = this.shadowRoot.querySelectorAll(".view");
for (const view of views) {
const isActive = view.id === `view${viewName.charAt(0).toUpperCase() + viewName.slice(1)}`;
view.classList.toggle("active", isActive);
}
// Update URL if requested
if (updateUrl) {
if (params.id) {
navigateToItem(viewName, params.id);
} else {
navigateToView(viewName);
}
}
// Emit event for components that need to know about route params
emit("router:viewChanged", { view: viewName, params });
}
}
customElements.define("ops-shell", OpsShell);