Files
botino/public/components/conversation-list.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

255 lines
10 KiB
JavaScript

import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
import { modal } from "../lib/modal.js";
class ConversationList extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.conversations = [];
this.selected = null;
this.tab = "chats"; // chats | users
this.users = [];
this.selectedUser = null;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
.box { background:var(--panel); border:1px solid var(--border); border-radius:var(--r-lg); padding:10px; margin-bottom:10px; }
.row { display:flex; gap:8px; align-items:center; }
input,select,button { background:var(--panel-2); color:var(--text); border:1px solid var(--border-hi); border-radius:var(--r-md); padding:8px; font-size:13px; }
button { cursor:pointer; }
button.ghost { background:transparent; }
button:disabled { opacity:.6; cursor:not-allowed; }
.tabs { display:flex; gap:8px; margin-bottom:10px; }
.tab { flex:1; text-align:center; padding:8px; border-radius:var(--r-md); border:1px solid var(--border-hi); cursor:pointer; color:var(--text-muted); background:var(--panel); }
.tab.active { border-color:var(--accent); color:var(--text); background:var(--panel-2); }
.list { display:flex; flex-direction:column; gap:8px; }
.item { background:var(--panel); border:1px solid var(--border); border-radius:var(--r-lg); padding:10px; cursor:pointer; }
.item:hover { border-color:#2b3b52; }
.item.active { border-color:var(--accent); }
.title { font-weight:800; }
.muted { color:var(--text-muted); font-size:12px; }
.chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }
.chip { display:inline-flex; align-items:center; gap:6px; padding:3px 8px; border-radius:999px; background:#1d2a3a; border:1px solid #243247; font-size:12px; color:var(--text-muted); }
.dot { width:8px; height:8px; border-radius:50%; }
.ok{ background:var(--ok) } .warn{ background:var(--warn) } .err{ background:var(--err) }
.actions { display:flex; gap:8px; justify-content:flex-end; margin-top:8px; flex-wrap:wrap; }
</style>
<div class="tabs">
<div class="tab active" id="tabChats">Chats</div>
<div class="tab" id="tabUsers">Usuarios</div>
</div>
<div class="box" id="filtersBox">
<div class="row">
<input id="q" style="flex:1" placeholder="Buscar chat_id / teléfono…" />
</div>
<div class="box" id="userActions" style="display:none; margin-top:8px">
<div class="actions" style="justify-content:flex-start">
<button class="ghost" id="uaSelect">Chat</button>
<button class="ghost" id="uaDeleteConv">Borrar Chat</button>
<button id="uaDeleteUser">Borrar User</button>
</div>
</div>
<div class="row" style="margin-top:8px">
<select id="status" style="flex:1">
<option value="">Status: all</option>
<option value="ok">ok</option>
<option value="warn">warn</option>
<option value="error">error</option>
</select>
<select id="state" style="flex:1">
<option value="">State: all</option>
<option>IDLE</option>
<option>CART</option>
<option>SHIPPING</option>
<option>AWAITING_HUMAN</option>
</select>
</div>
</div>
<div class="list" id="list"></div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("tabChats").onclick = () => this.setTab("chats");
this.shadowRoot.getElementById("tabUsers").onclick = () => this.setTab("users");
this.shadowRoot.getElementById("q").oninput = () => {
clearTimeout(this._t);
this._t = setTimeout(() => this.refresh(), 250);
};
this.shadowRoot.getElementById("status").onchange = () => this.refresh();
this.shadowRoot.getElementById("state").onchange = () => this.refresh();
// acciones del usuario seleccionado (solo en tab Users)
this.shadowRoot.getElementById("uaSelect").onclick = () => {
if (!this.selectedUser) return;
emit("ui:selectedChat", { chat_id: this.selectedUser.chat_id });
this.setTab("chats");
};
this.shadowRoot.getElementById("uaDeleteConv").onclick = async () => {
if (!this.selectedUser) return;
const chat_id = this.selectedUser.chat_id;
const confirmed = await modal.confirm(`¿Borrar conversación completa de ${chat_id}?`);
if (!confirmed) return;
await api.deleteConversation(chat_id);
this.selectedUser = null;
await this.refreshUsers();
};
this.shadowRoot.getElementById("uaDeleteUser").onclick = async () => {
if (!this.selectedUser) return;
const chat_id = this.selectedUser.chat_id;
const confirmed = await modal.confirm(`¿Borrar usuario ${chat_id}, sus conversaciones y el customer en Woo?`);
if (!confirmed) return;
await api.deleteUser(chat_id, { deleteWoo: true });
this.selectedUser = null;
await this.refreshUsers();
};
this._unsub1 = on("conversation:upsert", (conv) => {
if (this.tab !== "chats") return;
const idx = this.conversations.findIndex(x => x.chat_id === conv.chat_id);
if (idx >= 0) this.conversations[idx] = conv;
else this.conversations.unshift(conv);
this.render();
});
this.refresh();
}
disconnectedCallback() {
this._unsub1?.();
}
dot(status) {
const cls = status === "ok" ? "ok" : (status === "warn" ? "warn" : "err");
return `<span class="dot ${cls}"></span>`;
}
async refresh() {
try {
if (this.tab === "users") return await this.refreshUsers();
const q = this.shadowRoot.getElementById("q").value || "";
const status = this.shadowRoot.getElementById("status").value || "";
const state = this.shadowRoot.getElementById("state").value || "";
const data = await api.conversations({ q, status, state });
this.conversations = data.items || [];
this.render();
} catch (e) {
console.warn("[conversation-list] refresh failed", e);
}
}
async refreshUsers() {
try {
const q = this.shadowRoot.getElementById("q").value || "";
const data = await api.users({ q, limit: 200 });
this.users = data.items || [];
this.render();
} catch (e) {
console.warn("[conversation-list] refreshUsers failed", e);
}
}
setTab(tab) {
this.tab = tab;
this.shadowRoot.getElementById("tabChats").classList.toggle("active", tab === "chats");
this.shadowRoot.getElementById("tabUsers").classList.toggle("active", tab === "users");
// en users mantenemos el buscador; ocultamos filtros avanzados (status/state)
this.shadowRoot.getElementById("filtersBox").style.display = "block";
const adv = this.shadowRoot.getElementById("status")?.closest(".row");
if (adv) adv.style.display = tab === "chats" ? "flex" : "none";
const qEl = this.shadowRoot.getElementById("q");
qEl.placeholder = tab === "users" ? "Buscar usuario (chat_id / pushName)…" : "Buscar chat_id / teléfono…";
// acciones visibles solo en users (si no hay selección, quedan disabled)
this.renderSelectedUserActions();
this.refresh();
}
renderSelectedUserActions() {
const box = this.shadowRoot.getElementById("userActions");
const inUsers = this.tab === "users";
box.style.display = inUsers ? "block" : "none";
const hasSel = Boolean(this.selectedUser);
const b1 = this.shadowRoot.getElementById("uaSelect");
const b2 = this.shadowRoot.getElementById("uaDeleteConv");
const b3 = this.shadowRoot.getElementById("uaDeleteUser");
if (b1) b1.disabled = !hasSel;
if (b2) b2.disabled = !hasSel;
if (b3) b3.disabled = !hasSel;
}
render() {
const list = this.shadowRoot.getElementById("list");
list.innerHTML = "";
if (this.tab === "users") {
// panel de acciones
this.renderSelectedUserActions();
for (const u of this.users) {
const el = document.createElement("div");
el.className = "item" + (this.selectedUser?.chat_id === u.chat_id ? " active" : "");
const name = u.push_name || u.chat_id.replace(/@.+$/, "");
el.innerHTML = `
<div class="row">
<div style="flex:1">
<div class="title">${name}</div>
<div class="muted">${u.chat_id}</div>
<div class="muted">woo_customer_id: ${u.external_customer_id || "—"}</div>
</div>
</div>
`;
el.onclick = () => {
this.selectedUser = u;
this.render();
};
list.appendChild(el);
}
return;
}
for (const c of this.conversations) {
const el = document.createElement("div");
el.className = "item" + (c.chat_id === this.selected ? " active" : "");
el.innerHTML = `
<div class="row">
${this.dot(c.status)}
<div style="flex:1">
<div class="title">${c.from}</div>
<div class="muted">${c.chat_id}</div>
</div>
<button class="ghost" data-del="1">Borrar</button>
</div>
<div class="chips">
<span class="chip">state: ${c.state}</span>
<span class="chip">intent: ${c.intent}</span>
<span class="chip">last: ${new Date(c.last_activity).toLocaleTimeString()}</span>
</div>
`;
el.onclick = async (e) => {
if (e?.target?.dataset?.del) {
e.stopPropagation();
const confirmed = await modal.confirm(`¿Borrar conversación completa de ${c.chat_id}?`);
if (!confirmed) return;
await api.deleteConversation(c.chat_id);
if (this.selected === c.chat_id) this.selected = null;
await this.refresh();
return;
}
this.selected = c.chat_id;
this.render();
emit("ui:selectedChat", { chat_id: c.chat_id });
};
list.appendChild(el);
}
}
}
customElements.define("conversation-list", ConversationList);