ux improved

This commit is contained in:
Lucas Tettamanti
2026-01-17 04:13:35 -03:00
parent 98e3d78e3d
commit 63b9ecef61
35 changed files with 4266 additions and 75 deletions

View File

@@ -0,0 +1,278 @@
import { api } from "../lib/api.js";
class AliasesCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.products = [];
this.selected = null;
this.loading = false;
this.searchQuery = "";
this.editMode = null; // 'create' | 'edit' | null
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px; overflow:hidden; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.container { display:grid; grid-template-columns:1fr 400px; gap:16px; height:100%; }
.panel { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:16px; overflow:hidden; display:flex; flex-direction:column; }
.panel-title { font-size:14px; font-weight:700; color:#8aa0b5; text-transform:uppercase; letter-spacing:.4px; margin-bottom:12px; }
.toolbar { display:flex; gap:8px; margin-bottom:12px; }
input, select, textarea { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px 12px; font-size:13px; width:100%; }
input:focus, select:focus, textarea:focus { outline:none; border-color:#1f6feb; }
button { cursor:pointer; background:#1f6feb; color:#fff; border:none; border-radius:8px; padding:8px 16px; font-size:13px; }
button:hover { background:#1a5fd0; }
button:disabled { opacity:.5; cursor:not-allowed; }
button.secondary { background:#253245; }
button.secondary:hover { background:#2d3e52; }
button.danger { background:#e74c3c; }
button.danger:hover { background:#c0392b; }
.list { flex:1; overflow-y:auto; }
.item { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; margin-bottom:8px; cursor:pointer; transition:all .15s; }
.item:hover { border-color:#1f6feb; }
.item.active { border-color:#1f6feb; background:#111b2a; }
.item-alias { font-weight:600; color:#e7eef7; margin-bottom:4px; font-size:15px; }
.item-product { font-size:12px; color:#8aa0b5; }
.item-boost { color:#2ecc71; font-size:11px; }
.form { flex:1; overflow-y:auto; }
.form-empty { color:#8aa0b5; text-align:center; padding:40px; }
.field { margin-bottom:16px; }
.field label { display:block; font-size:12px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.field-hint { font-size:11px; color:#8aa0b5; margin-top:4px; }
.actions { display:flex; gap:8px; margin-top:16px; }
.loading { text-align:center; padding:40px; color:#8aa0b5; }
</style>
<div class="container">
<div class="panel">
<div class="panel-title">Equivalencias (Aliases)</div>
<div class="toolbar">
<input type="text" id="search" placeholder="Buscar alias..." style="flex:1" />
<button id="newBtn">+ Nuevo</button>
</div>
<div class="list" id="list">
<div class="loading">Cargando...</div>
</div>
</div>
<div class="panel">
<div class="panel-title" id="formTitle">Detalle</div>
<div class="form" id="form">
<div class="form-empty">Seleccioná un alias o creá uno nuevo</div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("search").oninput = (e) => {
this.searchQuery = e.target.value;
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => this.load(), 300);
};
this.shadowRoot.getElementById("newBtn").onclick = () => this.showCreateForm();
this.load();
this.loadProducts();
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.aliases({ q: this.searchQuery, limit: 500 });
this.items = data.items || [];
this.loading = false;
this.renderList();
} catch (e) {
console.error("Error loading aliases:", e);
this.items = [];
this.loading = false;
this.renderList();
}
}
async loadProducts() {
try {
const data = await api.products({ limit: 500 });
this.products = data.items || [];
} catch (e) {
console.error("Error loading products:", e);
this.products = [];
}
}
renderList() {
const list = this.shadowRoot.getElementById("list");
if (this.loading) {
list.innerHTML = `<div class="loading">Cargando...</div>`;
return;
}
if (!this.items.length) {
list.innerHTML = `<div class="loading">No se encontraron aliases</div>`;
return;
}
list.innerHTML = "";
for (const item of this.items) {
const el = document.createElement("div");
el.className = "item" + (this.selected?.alias === item.alias ? " active" : "");
const product = this.products.find(p => p.woo_product_id === item.woo_product_id);
const productName = product?.name || `ID: ${item.woo_product_id || "—"}`;
const boost = item.boost ? `+${item.boost}` : "";
el.innerHTML = `
<div class="item-alias">"${item.alias}"</div>
<div class="item-product">→ ${productName} ${boost ? `<span class="item-boost">(boost: ${boost})</span>` : ""}</div>
`;
el.onclick = () => {
this.selected = item;
this.editMode = "edit";
this.renderList();
this.renderForm();
};
list.appendChild(el);
}
}
showCreateForm() {
this.selected = null;
this.editMode = "create";
this.renderList();
this.renderForm();
}
renderForm() {
const form = this.shadowRoot.getElementById("form");
const title = this.shadowRoot.getElementById("formTitle");
if (!this.editMode) {
title.textContent = "Detalle";
form.innerHTML = `<div class="form-empty">Seleccioná un alias o creá uno nuevo</div>`;
return;
}
const isCreate = this.editMode === "create";
title.textContent = isCreate ? "Nuevo Alias" : "Editar Alias";
const alias = this.selected?.alias || "";
const wooProductId = this.selected?.woo_product_id || "";
const boost = this.selected?.boost || 0;
const categoryHint = this.selected?.category_hint || "";
const productOptions = this.products.map(p =>
`<option value="${p.woo_product_id}" ${p.woo_product_id === wooProductId ? "selected" : ""}>${p.name}</option>`
).join("");
form.innerHTML = `
<div class="field">
<label>Alias (lo que dice el usuario)</label>
<input type="text" id="aliasInput" value="${alias}" ${isCreate ? "" : "disabled"} placeholder="ej: chimi, vacio, bife" />
<div class="field-hint">Sin tildes, en minusculas. Ej: "chimi" mapea a "Chimichurri"</div>
</div>
<div class="field">
<label>Producto destino</label>
<select id="productInput">
<option value="">— Seleccionar producto —</option>
${productOptions}
</select>
</div>
<div class="field">
<label>Boost (puntuacion extra)</label>
<input type="number" id="boostInput" value="${boost}" min="0" max="10" step="0.1" />
<div class="field-hint">Valor entre 0 y 10. Mayor boost = mayor prioridad en resultados</div>
</div>
<div class="field">
<label>Categoria hint (opcional)</label>
<input type="text" id="categoryInput" value="${categoryHint}" placeholder="ej: carnes, bebidas" />
</div>
<div class="actions">
<button id="saveBtn">${isCreate ? "Crear" : "Guardar"}</button>
${!isCreate ? `<button id="deleteBtn" class="danger">Eliminar</button>` : ""}
<button id="cancelBtn" class="secondary">Cancelar</button>
</div>
`;
this.shadowRoot.getElementById("saveBtn").onclick = () => this.save();
this.shadowRoot.getElementById("cancelBtn").onclick = () => this.cancel();
if (!isCreate) {
this.shadowRoot.getElementById("deleteBtn").onclick = () => this.delete();
}
}
async save() {
const aliasInput = this.shadowRoot.getElementById("aliasInput").value.trim().toLowerCase();
const productInput = this.shadowRoot.getElementById("productInput").value;
const boostInput = parseFloat(this.shadowRoot.getElementById("boostInput").value) || 0;
const categoryInput = this.shadowRoot.getElementById("categoryInput").value.trim();
if (!aliasInput) {
alert("El alias es requerido");
return;
}
if (!productInput) {
alert("Seleccioná un producto");
return;
}
const data = {
alias: aliasInput,
woo_product_id: parseInt(productInput, 10),
boost: boostInput,
category_hint: categoryInput || null,
};
try {
if (this.editMode === "create") {
await api.createAlias(data);
} else {
await api.updateAlias(this.selected.alias, data);
}
this.editMode = null;
this.selected = null;
await this.load();
this.renderForm();
} catch (e) {
console.error("Error saving alias:", e);
alert("Error guardando: " + (e.message || e));
}
}
async delete() {
if (!this.selected?.alias) return;
if (!confirm(`¿Eliminar el alias "${this.selected.alias}"?`)) return;
try {
await api.deleteAlias(this.selected.alias);
this.editMode = null;
this.selected = null;
await this.load();
this.renderForm();
} catch (e) {
console.error("Error deleting alias:", e);
alert("Error eliminando: " + (e.message || e));
}
}
cancel() {
this.editMode = null;
this.selected = null;
this.renderList();
this.renderForm();
}
}
customElements.define("aliases-crud", AliasesCrud);

View File

@@ -9,39 +9,60 @@ class ChatSimulator extends HTMLElement {
this._sending = false;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; margin-bottom:10px; }
.muted { color:#8aa0b5; font-size:12px; }
:host { display:block; height:100%; overflow:hidden; }
* { box-sizing:border-box; }
.container { display:grid; grid-template-columns:1fr 1fr; gap:0; height:100%; overflow:hidden; }
.col { display:flex; flex-direction:column; padding:10px 12px; border-right:1px solid #1e2a3a; min-width:0; overflow:hidden; }
.col:last-child { border-right:none; }
.muted { color:#8aa0b5; font-size:11px; margin-bottom:6px; }
.row { display:flex; gap:8px; align-items:center; }
input,textarea,button { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px; font-size:13px; }
textarea { width:100%; min-height:70px; resize:vertical; }
button { cursor:pointer; }
input,textarea,button { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:6px; padding:6px 8px; font-size:12px; box-sizing:border-box; }
input { width:100%; min-width:0; }
textarea { width:100%; resize:none; height:186px; min-width:0; margin-bottom:10px;}
button { cursor:pointer; white-space:nowrap; }
button.primary { background:#1f6feb; border-color:#1f6feb; }
button:disabled { opacity:.6; cursor:not-allowed; }
.status { margin-top:8px; font-size:12px; color:#8aa0b5; }
.status { font-size:11px; color:#8aa0b5; margin-top:6px; }
.inputs-col { display:flex; flex-direction:column; gap:6px; flex:1; overflow:hidden; min-width:0; }
.field { display:flex; flex-direction:column; min-width:0; }
.field label { font-size:10px; color:#8aa0b5; margin-bottom:2px; }
.msg-col { display:flex; flex-direction:column; min-width:0; }
.msg-bottom { display:flex; gap:8px; align-items:center; margin-top:6px; }
</style>
<div class="box">
<div class="muted">Evolution Sim (único chat)</div>
<div class="row" style="margin-top:8px">
<input id="instance" style="flex:1" value="Piaf" placeholder="tenant/instance key" />
<div class="container">
<div class="col">
<div class="muted">Evolution Sim</div>
<div class="inputs-col">
<div class="field">
<label>Instance</label>
<input id="instance" value="Piaf" placeholder="tenant" />
</div>
<div class="field">
<label>From (remoteJid)</label>
<input id="evoFrom" value="5491133230322@s.whatsapp.net" placeholder="from" />
</div>
<div class="field">
<label>To</label>
<input id="evoTo" value="5491137887040@s.whatsapp.net" placeholder="to" />
</div>
<div class="field">
<label>Push Name</label>
<input id="pushName" value="test_lucas" placeholder="pushName" />
</div>
</div>
</div>
<div class="row" style="margin-top:8px">
<input id="evoFrom" style="flex:1" value="5491133230322@s.whatsapp.net" placeholder="from (remoteJid)" />
<div class="col">
<div class="muted">Mensaje</div>
<div class="msg-col">
<textarea id="evoText" placeholder="Texto a enviar..."></textarea>
<div class="msg-bottom">
<button class="primary" id="sendEvo">Send</button>
<button id="retry">Retry</button>
<span class="status" id="status">—</span>
</div>
</div>
</div>
<div class="row" style="margin-top:8px">
<input id="evoTo" style="flex:1" value="5491137887040@s.whatsapp.net" placeholder="to (destino receptor)" />
</div>
<div class="row" style="margin-top:8px">
<input id="pushName" style="flex:1" value="test_lucas" placeholder="pushName (opcional)" />
</div>
<div class="muted" style="margin-top:7px">Enviar mensaje</div>
<textarea id="evoText" style="margin-top:8px" placeholder="Texto a enviar por Evolution…"></textarea>
<div class="row" style="margin-top:8px">
<button class="primary" id="sendEvo" style="flex:1">Send</button>
<button id="retry" style="width:140px">Retry last</button>
</div>
<div class="status" id="status">—</div>
</div>
`;
}
@@ -123,6 +144,17 @@ class ChatSimulator extends HTMLElement {
last_run_id: null,
});
emit("ui:selectedChat", { chat_id: from });
// Optimistic: mostrar burbuja del usuario inmediatamente
emit("message:optimistic", {
chat_id: from,
message_id: `optimistic-${Date.now()}`,
direction: "in",
text,
ts: new Date().toISOString(),
provider: "sim",
pushName: pushName || "test_lucas",
});
const payload = payloadOverride || buildPayload({ text, from, to, instance, pushName });
this._lastPayload = { ...payload, body: { ...payload.body, data: { ...payload.body.data, key: { ...payload.body.data.key, id: genId() } } } };

View File

@@ -0,0 +1,308 @@
import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ConversationInspector extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.chatId = null;
this.messages = [];
this.runs = [];
this.rowOrder = [];
this.rowMap = new Map();
this.heights = new Map();
this._playing = false;
this._playIdx = 0;
this._timer = null;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; height:100%; overflow:hidden; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; height:100%; display:flex; flex-direction:column; min-height:0; box-sizing:border-box; }
.row { display:flex; gap:8px; align-items:center; }
.muted { color:#8aa0b5; font-size:12px; }
.title { font-weight:800; }
.toolbar { display:flex; gap:8px; margin-top:8px; align-items:center; }
button { cursor:pointer; background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px; font-size:13px; }
.list { display:flex; flex-direction:column; gap:0; overflow-y:auto; padding-right:6px; margin-top:8px; flex:1; min-height:0; }
.item { border:1px solid #253245; border-radius:12px; padding:8px 10px; background:#0f1520; font-size:12px; margin-bottom:12px; box-sizing:border-box; }
.item.in { background:#0f1520; border-color:#2a3a55; }
.item.out { background:#111b2a; border-color:#2a3a55; }
.item.active { outline:2px solid #1f6feb; box-shadow: 0 0 0 2px rgba(31,111,235,.25); }
.kv { display:grid; grid-template-columns:70px 1fr; gap:6px 10px; }
.k { color:#8aa0b5; font-size:11px; letter-spacing:.4px; text-transform:uppercase; }
.v { font-size:12px; color:#e7eef7; }
.chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:6px; }
.chip { display:inline-flex; align-items:center; gap:6px; padding:2px 6px; border-radius:999px; background:#1d2a3a; border:1px solid #243247; font-size:11px; color:#8aa0b5; }
.cart { margin-top:6px; font-size:11px; color:#c7d8ee; }
.tool { margin-top:6px; font-size:11px; color:#8aa0b5; }
.dot { width:8px; height:8px; border-radius:50%; }
.ok { background:#2ecc71; } .warn { background:#f1c40f; } .err { background:#e74c3c; }
</style>
<div class="box">
<div class="muted">Inspector</div>
<div class="title" id="chat">—</div>
<div class="muted" id="meta">Seleccioná una conversación.</div>
<div class="toolbar">
<button id="play">Play</button>
<button id="pause">Pause</button>
<button id="step">Step</button>
<span class="muted" id="count"></span>
</div>
<div class="list" id="list"></div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("play").onclick = () => this.play();
this.shadowRoot.getElementById("pause").onclick = () => this.pause();
this.shadowRoot.getElementById("step").onclick = () => this.step();
this._unsubSel = on("ui:selectedChat", async ({ chat_id }) => {
this.chatId = chat_id;
await this.loadData();
});
this._unsubRun = on("run:created", (run) => {
if (this.chatId && run.chat_id === this.chatId) {
this.loadData();
}
});
this._unsubLayout = on("ui:bubblesLayout", ({ chat_id, items }) => {
if (!this.chatId || chat_id !== this.chatId) return;
this.heights = new Map((items || []).map((it) => [it.message_id, it.height || 0]));
this.applyHeights();
});
this._unsubScroll = on("ui:chatScroll", ({ chat_id, scrollTop }) => {
if (!this.chatId || chat_id !== this.chatId) return;
const list = this.shadowRoot.getElementById("list");
list.scrollTop = scrollTop || 0;
});
this._unsubSelectMessage = on("ui:selectedMessage", ({ message }) => {
const messageId = message?.message_id || null;
if (messageId) this.highlight(messageId);
});
}
disconnectedCallback() {
this._unsubSel?.();
this._unsubRun?.();
this._unsubLayout?.();
this._unsubScroll?.();
this._unsubSelectMessage?.();
this.pause();
}
async loadData() {
const chatEl = this.shadowRoot.getElementById("chat");
const metaEl = this.shadowRoot.getElementById("meta");
const countEl = this.shadowRoot.getElementById("count");
const list = this.shadowRoot.getElementById("list");
chatEl.textContent = this.chatId || "—";
metaEl.textContent = "Cargando…";
countEl.textContent = "";
list.innerHTML = "";
if (!this.chatId) {
metaEl.textContent = "Seleccioná una conversación.";
return;
}
try {
const [msgs, runs] = await Promise.all([
api.messages({ chat_id: this.chatId, limit: 200 }),
api.runs({ chat_id: this.chatId, limit: 200 }),
]);
this.messages = msgs.items || [];
this.runs = runs.items || [];
this.render();
this.applyHeights();
} catch (e) {
metaEl.textContent = `Error cargando: ${String(e?.message || e)}`;
this.messages = [];
this.runs = [];
}
}
runMap() {
const map = new Map();
for (const r of this.runs || []) {
map.set(r.run_id, r);
}
return map;
}
buildRows() {
const runsById = this.runMap();
const rows = [];
let nextRun = null;
for (let i = this.messages.length - 1; i >= 0; i--) {
const msg = this.messages[i];
const run = msg?.run_id ? runsById.get(msg.run_id) : null;
if (run) nextRun = run;
rows[i] = { message: msg, run, nextRun };
}
return rows;
}
formatCart(items) {
const list = Array.isArray(items) ? items : [];
if (!list.length) return "—";
return list
.map((it) => {
const label = it.label || it.name || `#${it.product_id}`;
const qty = it.quantity != null ? `${it.quantity}` : "?";
const unit = it.unit || "";
return `${label} (${qty}${unit ? " " + unit : ""})`;
})
.join(" · ");
}
toolSummary(tools = []) {
return tools.map((t) => ({
type: t.type || t.name || "tool",
ok: t.ok !== false,
error: t.error || null,
}));
}
render() {
const metaEl = this.shadowRoot.getElementById("meta");
const countEl = this.shadowRoot.getElementById("count");
const list = this.shadowRoot.getElementById("list");
metaEl.textContent = `Inspector de ${this.messages.length} mensajes.`;
countEl.textContent = this.messages.length ? `${this.messages.length} filas` : "";
list.innerHTML = "";
this.rowMap.clear();
this.rowOrder = [];
const rows = this.buildRows();
for (const row of rows) {
const msg = row.message;
const run = row.run;
const dir = msg?.direction === "in" ? "in" : "out";
const el = document.createElement("div");
el.className = `item ${dir}`;
el.dataset.messageId = msg.message_id;
const intent = run?.llm_output?.intent || "—";
const nextState = run?.llm_output?.next_state || "—";
const prevState = row.nextRun?.prev_state || "—";
const basket = run?.llm_output?.basket_resolved?.items || [];
const tools = this.toolSummary(run?.tools || []);
const llmMeta = run?.llm_output?._llm || null;
const llmStatus = llmMeta?.audit?.validation?.ok === false ? "warn" : "ok";
const llmNote = llmMeta?.audit?.validation?.ok === false
? "NLU inválido (fallback)"
: llmMeta?.audit?.validation?.retried
? "NLU ok (retry)"
: "NLU ok";
el.innerHTML = `
<div class="kv">
<div class="k">${dir === "in" ? "IN" : "OUT"}</div>
<div class="v">${new Date(msg.ts).toLocaleString()}</div>
<div class="k">STATE</div>
<div class="v">${dir === "out" ? nextState : prevState}</div>
<div class="k">INTENT</div>
<div class="v">${dir === "out" ? intent : "—"}</div>
<div class="k">NLU</div>
<div class="v">${dir === "out" && llmMeta ? llmNote : "—"}</div>
</div>
<div class="cart"><strong>Carrito:</strong> ${dir === "out" ? this.formatCart(basket) : "—"}</div>
<div class="chips">
${tools
.map(
(t) =>
`<span class="chip"><span class="dot ${t.ok ? "ok" : "err"}"></span>${t.type}</span>`
)
.join("")}
</div>
`;
el.onclick = () => {
this.highlight(msg.message_id);
};
list.appendChild(el);
this.rowMap.set(msg.message_id, el);
this.rowOrder.push(msg.message_id);
}
}
applyHeights() {
const BUBBLE_MARGIN = 12; // same as .bubble margin-bottom in run-timeline
const MIN_ITEM_HEIGHT = 120; // minimum height for inspector items
for (const [messageId, el] of this.rowMap.entries()) {
const bubbleHeight = this.heights.get(messageId) || 0;
// bubbleHeight includes offsetHeight + marginBottom
const bubbleContentHeight = Math.max(0, bubbleHeight - BUBBLE_MARGIN);
// Use the max between bubble height and our minimum
const targetHeight = Math.max(bubbleContentHeight, MIN_ITEM_HEIGHT);
el.style.minHeight = `${targetHeight}px`;
el.style.marginBottom = `${BUBBLE_MARGIN}px`;
}
// After applying, emit final heights back so bubbles can sync
requestAnimationFrame(() => this.emitInspectorHeights());
}
emitInspectorHeights() {
const items = [];
for (const [messageId, el] of this.rowMap.entries()) {
const styles = window.getComputedStyle(el);
const marginBottom = parseInt(styles.marginBottom || "0", 10) || 0;
items.push({
message_id: messageId,
height: (el.offsetHeight || 0) + marginBottom,
});
}
emit("ui:inspectorLayout", { chat_id: this.chatId, items });
}
highlight(messageId) {
for (const [id, el] of this.rowMap.entries()) {
el.classList.toggle("active", id === messageId);
}
emit("ui:highlightMessage", { message_id: messageId });
const idx = this.rowOrder.indexOf(messageId);
if (idx >= 0) this._playIdx = idx;
}
play() {
if (this._playing) return;
this._playing = true;
this._timer = setInterval(() => this.step(), 800);
}
pause() {
this._playing = false;
if (this._timer) clearInterval(this._timer);
this._timer = null;
}
step() {
if (!this.rowOrder.length) return;
if (this._playIdx >= this.rowOrder.length) {
this.pause();
return;
}
const messageId = this.rowOrder[this._playIdx];
this.highlight(messageId);
this._playIdx += 1;
}
}
customElements.define("conversation-inspector", ConversationInspector);

View File

@@ -0,0 +1,267 @@
import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ConversationsCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.selected = null;
this.loading = false;
this.searchQuery = "";
this.statusFilter = "";
this.stateFilter = "";
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px; overflow:hidden; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.container { display:grid; grid-template-columns:1fr 450px; gap:16px; height:100%; }
.panel { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:16px; overflow:hidden; display:flex; flex-direction:column; }
.panel-title { font-size:14px; font-weight:700; color:#8aa0b5; text-transform:uppercase; letter-spacing:.4px; margin-bottom:12px; }
.toolbar { display:flex; gap:8px; margin-bottom:12px; flex-wrap:wrap; }
input, select { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px 12px; font-size:13px; }
input:focus, select:focus { outline:none; border-color:#1f6feb; }
button { cursor:pointer; background:#1f6feb; color:#fff; border:none; border-radius:8px; padding:8px 16px; font-size:13px; }
button:hover { background:#1a5fd0; }
button:disabled { opacity:.5; cursor:not-allowed; }
button.secondary { background:#253245; }
button.secondary:hover { background:#2d3e52; }
button.danger { background:#e74c3c; }
button.danger:hover { background:#c0392b; }
.list { flex:1; overflow-y:auto; }
.item { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; margin-bottom:8px; cursor:pointer; transition:all .15s; }
.item:hover { border-color:#1f6feb; }
.item.active { border-color:#1f6feb; background:#111b2a; }
.item-header { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
.item-name { font-weight:600; color:#e7eef7; flex:1; }
.item-meta { font-size:12px; color:#8aa0b5; }
.dot { width:8px; height:8px; border-radius:50%; flex-shrink:0; }
.ok { background:#2ecc71; } .warn { background:#f1c40f; } .err { background:#e74c3c; }
.chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:6px; }
.chip { display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; background:#253245; color:#8aa0b5; }
.detail { flex:1; overflow-y:auto; }
.detail-empty { color:#8aa0b5; text-align:center; padding:40px; }
.field { margin-bottom:16px; }
.field label { display:block; font-size:12px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.field-value { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:10px 12px; color:#e7eef7; font-size:13px; }
.actions { display:flex; gap:8px; margin-top:16px; flex-wrap:wrap; }
.loading { text-align:center; padding:40px; color:#8aa0b5; }
</style>
<div class="container">
<div class="panel">
<div class="panel-title">Conversaciones</div>
<div class="toolbar">
<input type="text" id="search" placeholder="Buscar chat_id o telefono..." style="flex:1;min-width:150px" />
<select id="status">
<option value="">Status: todos</option>
<option value="ok">ok</option>
<option value="warn">warn</option>
<option value="error">error</option>
</select>
<select id="state">
<option value="">State: todos</option>
<option>IDLE</option>
<option>BROWSING</option>
<option>BUILDING_ORDER</option>
<option>WAITING_ADDRESS</option>
<option>WAITING_PAYMENT</option>
<option>COMPLETED</option>
</select>
</div>
<div class="list" id="list">
<div class="loading">Cargando...</div>
</div>
</div>
<div class="panel">
<div class="panel-title" id="detailTitle">Detalle</div>
<div class="detail" id="detail">
<div class="detail-empty">Selecciona una conversacion</div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("search").oninput = (e) => {
this.searchQuery = e.target.value;
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => this.load(), 300);
};
this.shadowRoot.getElementById("status").onchange = (e) => {
this.statusFilter = e.target.value;
this.load();
};
this.shadowRoot.getElementById("state").onchange = (e) => {
this.stateFilter = e.target.value;
this.load();
};
this._unsubUpsert = on("conversation:upsert", (conv) => {
const idx = this.items.findIndex(x => x.chat_id === conv.chat_id);
if (idx >= 0) this.items[idx] = conv;
else this.items.unshift(conv);
this.renderList();
});
this.load();
}
disconnectedCallback() {
this._unsubUpsert?.();
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.conversations({
q: this.searchQuery,
status: this.statusFilter,
state: this.stateFilter
});
this.items = data.items || [];
this.loading = false;
this.renderList();
} catch (e) {
console.error("Error loading conversations:", e);
this.items = [];
this.loading = false;
this.renderList();
}
}
renderList() {
const list = this.shadowRoot.getElementById("list");
if (this.loading) {
list.innerHTML = `<div class="loading">Cargando...</div>`;
return;
}
if (!this.items.length) {
list.innerHTML = `<div class="loading">No se encontraron conversaciones</div>`;
return;
}
list.innerHTML = "";
for (const item of this.items) {
const el = document.createElement("div");
el.className = "item" + (this.selected?.chat_id === item.chat_id ? " active" : "");
const dotClass = item.status === "ok" ? "ok" : (item.status === "warn" ? "warn" : "err");
const time = item.last_activity ? new Date(item.last_activity).toLocaleString() : "—";
el.innerHTML = `
<div class="item-header">
<span class="dot ${dotClass}"></span>
<span class="item-name">${item.from || item.chat_id}</span>
</div>
<div class="item-meta">${item.chat_id}</div>
<div class="chips">
<span class="chip">state: ${item.state || "—"}</span>
<span class="chip">intent: ${item.intent || "—"}</span>
<span class="chip">${time}</span>
</div>
`;
el.onclick = () => {
this.selected = item;
this.renderList();
this.renderDetail();
};
list.appendChild(el);
}
}
renderDetail() {
const detail = this.shadowRoot.getElementById("detail");
const title = this.shadowRoot.getElementById("detailTitle");
if (!this.selected) {
title.textContent = "Detalle";
detail.innerHTML = `<div class="detail-empty">Selecciona una conversacion</div>`;
return;
}
const c = this.selected;
title.textContent = c.from || c.chat_id;
detail.innerHTML = `
<div class="field">
<label>Chat ID</label>
<div class="field-value">${c.chat_id}</div>
</div>
<div class="field">
<label>From</label>
<div class="field-value">${c.from || "—"}</div>
</div>
<div class="field">
<label>Estado</label>
<div class="field-value">${c.state || "—"}</div>
</div>
<div class="field">
<label>Intent</label>
<div class="field-value">${c.intent || "—"}</div>
</div>
<div class="field">
<label>Status</label>
<div class="field-value">${c.status || "—"}</div>
</div>
<div class="field">
<label>Ultima actividad</label>
<div class="field-value">${c.last_activity ? new Date(c.last_activity).toLocaleString() : "—"}</div>
</div>
<div class="field">
<label>Ultimo run</label>
<div class="field-value">${c.last_run_id || "—"}</div>
</div>
<div class="actions">
<button id="openChat">Abrir Chat</button>
<button id="retryLast" class="secondary">Retry Last</button>
<button id="deleteConv" class="danger">Eliminar</button>
</div>
`;
detail.scrollTop = 0;
this.shadowRoot.getElementById("openChat").onclick = () => {
emit("ui:selectedChat", { chat_id: c.chat_id });
emit("ui:switchView", { view: "chat" });
};
this.shadowRoot.getElementById("retryLast").onclick = async () => {
try {
await api.retryLast(c.chat_id);
alert("Retry ejecutado");
} catch (e) {
alert("Error: " + (e.message || e));
}
};
this.shadowRoot.getElementById("deleteConv").onclick = async () => {
if (!confirm(`¿Eliminar la conversacion de "${c.chat_id}"?`)) return;
try {
await api.deleteConversation(c.chat_id);
this.selected = null;
await this.load();
this.renderDetail();
} catch (e) {
alert("Error: " + (e.message || e));
}
};
}
}
customElements.define("conversations-crud", ConversationsCrud);

View File

@@ -4,38 +4,87 @@ class OpsShell extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this._currentView = "chat";
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); }
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; }
.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); }
.layout { flex:1; display:grid; grid-template-columns:320px 1fr 360px; min-height:0; }
.col { border-right:1px solid var(--line); min-height:0; overflow:auto; }
.col:last-child { border-right:none; }
.mid { display:flex; flex-direction:column; min-height:0; }
.midTop { flex:1; min-height:0; overflow:auto; border-bottom:1px solid var(--line); }
.midBottom { min-height:220px; overflow:auto; }
/* 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">
<button class="nav-btn active" data-view="chat">Chat</button>
<button class="nav-btn" data-view="conversations">Conversaciones</button>
<button class="nav-btn" data-view="users">Usuarios</button>
<button class="nav-btn" data-view="products">Productos</button>
<button class="nav-btn" data-view="aliases">Equivalencias</button>
<button class="nav-btn" data-view="recommendations">Recomendaciones</button>
</nav>
<div class="spacer"></div>
<div class="status" id="sseStatus">SSE: connecting…</div>
</header>
<div class="layout">
<div class="col"><conversation-list></conversation-list></div>
<div class="col mid">
<div class="midTop"><run-timeline></run-timeline></div>
<div class="midBottom"><chat-simulator></chat-simulator></div>
<div id="viewChat" class="view active">
<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="viewRecommendations" class="view">
<div class="layout-crud">
<recommendations-crud></recommendations-crud>
</div>
<div class="col"><debug-panel></debug-panel></div>
</div>
</div>
`;
@@ -46,10 +95,39 @@ class OpsShell extends HTMLElement {
const el = this.shadowRoot.getElementById("sseStatus");
el.textContent = s.ok ? "SSE: connected" : "SSE: disconnected (retrying…)";
});
// Listen for view switch requests from other components
this._unsubSwitch = on("ui:switchView", ({ view }) => {
if (view) this.setView(view);
});
// Navigation
const navBtns = this.shadowRoot.querySelectorAll(".nav-btn");
for (const btn of navBtns) {
btn.onclick = () => this.setView(btn.dataset.view);
}
}
disconnectedCallback() {
this._unsub?.();
this._unsubSwitch?.();
}
setView(viewName) {
this._currentView = viewName;
// 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);
}
}
}

View File

@@ -0,0 +1,267 @@
import { api } from "../lib/api.js";
class ProductsCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.selected = null;
this.loading = false;
this.searchQuery = "";
this.stockFilter = false;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px; overflow:hidden; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.container { display:grid; grid-template-columns:1fr 400px; gap:16px; height:100%; }
.panel { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:16px; overflow:hidden; display:flex; flex-direction:column; }
.panel-title { font-size:14px; font-weight:700; color:#8aa0b5; text-transform:uppercase; letter-spacing:.4px; margin-bottom:12px; }
.toolbar { display:flex; gap:8px; margin-bottom:12px; }
input, select { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px 12px; font-size:13px; }
input:focus, select:focus { outline:none; border-color:#1f6feb; }
input { flex:1; }
button { cursor:pointer; background:#1f6feb; color:#fff; border:none; border-radius:8px; padding:8px 16px; font-size:13px; }
button:hover { background:#1a5fd0; }
button:disabled { opacity:.5; cursor:not-allowed; }
button.secondary { background:#253245; }
button.secondary:hover { background:#2d3e52; }
.list { flex:1; overflow-y:auto; }
.item { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; margin-bottom:8px; cursor:pointer; transition:all .15s; }
.item:hover { border-color:#1f6feb; }
.item.active { border-color:#1f6feb; background:#111b2a; }
.item-name { font-weight:600; color:#e7eef7; margin-bottom:4px; }
.item-meta { font-size:12px; color:#8aa0b5; }
.item-price { color:#2ecc71; font-weight:600; }
.detail { flex:1; overflow-y:auto; }
.detail-empty { color:#8aa0b5; text-align:center; padding:40px; }
.field { margin-bottom:16px; }
.field label { display:block; font-size:12px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.field-value { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:10px 12px; color:#e7eef7; font-size:13px; }
.field-value.json { font-family:monospace; font-size:11px; white-space:pre-wrap; max-height:200px; overflow-y:auto; }
.stats { display:flex; gap:16px; margin-bottom:16px; }
.stat { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; flex:1; text-align:center; cursor:pointer; transition:all .15s; }
.stat:hover { border-color:#1f6feb; }
.stat.active { border-color:#1f6feb; background:#111b2a; }
.stat-value { font-size:24px; font-weight:700; color:#1f6feb; }
.stat-label { font-size:11px; color:#8aa0b5; text-transform:uppercase; margin-top:4px; }
.loading { text-align:center; padding:40px; color:#8aa0b5; }
.badge { display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; background:#253245; color:#8aa0b5; margin-left:8px; }
.badge.stock { background:#0f2a1a; color:#2ecc71; }
.badge.nostock { background:#241214; color:#e74c3c; }
</style>
<div class="container">
<div class="panel">
<div class="panel-title">Productos</div>
<div class="stats">
<div class="stat" id="statTotal">
<div class="stat-value" id="totalCount">—</div>
<div class="stat-label">Total</div>
</div>
<div class="stat" id="statStock">
<div class="stat-value" id="inStockCount">—</div>
<div class="stat-label">En Stock</div>
</div>
</div>
<div class="toolbar">
<input type="text" id="search" placeholder="Buscar por nombre o SKU..." />
<button id="syncBtn" class="secondary">Sync Woo</button>
</div>
<div class="list" id="list">
<div class="loading">Cargando productos...</div>
</div>
</div>
<div class="panel">
<div class="panel-title">Detalle</div>
<div class="detail" id="detail">
<div class="detail-empty">Seleccioná un producto para ver detalles</div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("search").oninput = (e) => {
this.searchQuery = e.target.value;
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => this.load(), 300);
};
this.shadowRoot.getElementById("syncBtn").onclick = () => this.syncFromWoo();
// Stats click handlers
this.shadowRoot.getElementById("statTotal").onclick = () => {
this.stockFilter = false;
this.renderList();
this.updateStatStyles();
};
this.shadowRoot.getElementById("statStock").onclick = () => {
this.stockFilter = !this.stockFilter;
this.renderList();
this.updateStatStyles();
};
this.load();
}
updateStatStyles() {
const statTotal = this.shadowRoot.getElementById("statTotal");
const statStock = this.shadowRoot.getElementById("statStock");
statTotal.classList.toggle("active", !this.stockFilter);
statStock.classList.toggle("active", this.stockFilter);
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.products({ q: this.searchQuery, limit: 2000 });
this.items = data.items || [];
this.loading = false;
this.renderList();
this.renderStats();
} catch (e) {
console.error("Error loading products:", e);
this.items = [];
this.loading = false;
this.renderList();
}
}
async syncFromWoo() {
const btn = this.shadowRoot.getElementById("syncBtn");
btn.disabled = true;
btn.textContent = "Sincronizando...";
try {
await api.syncProducts();
await this.load();
} catch (e) {
console.error("Error syncing products:", e);
alert("Error sincronizando: " + (e.message || e));
} finally {
btn.disabled = false;
btn.textContent = "Sync Woo";
}
}
renderStats() {
const total = this.items.length;
const inStock = this.items.filter(p => p.stock_status === "instock" || p.payload?.stock_status === "instock").length;
this.shadowRoot.getElementById("totalCount").textContent = total;
this.shadowRoot.getElementById("inStockCount").textContent = inStock;
}
renderList() {
const list = this.shadowRoot.getElementById("list");
if (this.loading) {
list.innerHTML = `<div class="loading">Cargando productos...</div>`;
return;
}
// Filter items based on stock filter
const filteredItems = this.stockFilter
? this.items.filter(p => p.stock_status === "instock" || p.payload?.stock_status === "instock")
: this.items;
if (!filteredItems.length) {
list.innerHTML = `<div class="loading">No se encontraron productos</div>`;
return;
}
list.innerHTML = "";
for (const item of filteredItems) {
const el = document.createElement("div");
el.className = "item" + (this.selected?.woo_product_id === item.woo_product_id ? " active" : "");
const price = item.price != null ? `$${Number(item.price).toLocaleString()}` : "—";
const sku = item.sku || "—";
const stock = item.stock_status || item.payload?.stock_status || "unknown";
const stockBadge = stock === "instock"
? `<span class="badge stock">En stock</span>`
: `<span class="badge nostock">Sin stock</span>`;
el.innerHTML = `
<div class="item-name">${item.name || "Sin nombre"} ${stockBadge}</div>
<div class="item-meta">
<span class="item-price">${price}</span> ·
SKU: ${sku} ·
ID: ${item.woo_product_id}
</div>
`;
el.onclick = () => {
this.selected = item;
this.renderList();
this.renderDetail();
// Scroll detail panel to top
const detail = this.shadowRoot.getElementById("detail");
if (detail) detail.scrollTop = 0;
};
list.appendChild(el);
}
}
renderDetail() {
const detail = this.shadowRoot.getElementById("detail");
if (!this.selected) {
detail.innerHTML = `<div class="detail-empty">Seleccioná un producto para ver detalles</div>`;
return;
}
const p = this.selected;
const categories = (p.payload?.categories || []).map(c => c.name).join(", ") || "—";
const attributes = (p.payload?.attributes || []).map(a => `${a.name}: ${a.options?.join(", ")}`).join("; ") || "—";
detail.innerHTML = `
<div class="field">
<label>Nombre</label>
<div class="field-value">${p.name || "—"}</div>
</div>
<div class="field">
<label>ID WooCommerce</label>
<div class="field-value">${p.woo_product_id}</div>
</div>
<div class="field">
<label>SKU</label>
<div class="field-value">${p.sku || "—"}</div>
</div>
<div class="field">
<label>Precio</label>
<div class="field-value">${p.price != null ? `$${Number(p.price).toLocaleString()} ${p.currency || ""}` : "—"}</div>
</div>
<div class="field">
<label>Categorías</label>
<div class="field-value">${categories}</div>
</div>
<div class="field">
<label>Atributos</label>
<div class="field-value">${attributes}</div>
</div>
<div class="field">
<label>Última actualización</label>
<div class="field-value">${p.refreshed_at ? new Date(p.refreshed_at).toLocaleString() : "—"}</div>
</div>
<div class="field">
<label>Payload completo</label>
<div class="field-value json">${JSON.stringify(p.payload || {}, null, 2)}</div>
</div>
`;
}
}
customElements.define("products-crud", ProductsCrud);

View File

@@ -0,0 +1,320 @@
import { api } from "../lib/api.js";
class RecommendationsCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.selected = null;
this.loading = false;
this.searchQuery = "";
this.editMode = null; // 'create' | 'edit' | null
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px; overflow:hidden; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.container { display:grid; grid-template-columns:1fr 450px; gap:16px; height:100%; }
.panel { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:16px; overflow:hidden; display:flex; flex-direction:column; }
.panel-title { font-size:14px; font-weight:700; color:#8aa0b5; text-transform:uppercase; letter-spacing:.4px; margin-bottom:12px; }
.toolbar { display:flex; gap:8px; margin-bottom:12px; }
input, select, textarea { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px 12px; font-size:13px; width:100%; }
input:focus, select:focus, textarea:focus { outline:none; border-color:#1f6feb; }
textarea { min-height:60px; resize:vertical; font-size:13px; }
button { cursor:pointer; background:#1f6feb; color:#fff; border:none; border-radius:8px; padding:8px 16px; font-size:13px; }
button:hover { background:#1a5fd0; }
button:disabled { opacity:.5; cursor:not-allowed; }
button.secondary { background:#253245; }
button.secondary:hover { background:#2d3e52; }
button.danger { background:#e74c3c; }
button.danger:hover { background:#c0392b; }
.list { flex:1; overflow-y:auto; }
.item { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; margin-bottom:8px; cursor:pointer; transition:all .15s; }
.item:hover { border-color:#1f6feb; }
.item.active { border-color:#1f6feb; background:#111b2a; }
.item-key { font-weight:600; color:#e7eef7; margin-bottom:4px; display:flex; align-items:center; gap:8px; }
.item-trigger { font-size:12px; color:#8aa0b5; margin-bottom:4px; }
.item-queries { font-size:11px; color:#2ecc71; }
.badge { display:inline-block; padding:2px 8px; border-radius:999px; font-size:10px; }
.badge.active { background:#0f2a1a; color:#2ecc71; }
.badge.inactive { background:#241214; color:#e74c3c; }
.badge.priority { background:#253245; color:#8aa0b5; }
.form { flex:1; overflow-y:auto; }
.form-empty { color:#8aa0b5; text-align:center; padding:40px; }
.field { margin-bottom:16px; }
.field label { display:block; font-size:12px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.field-hint { font-size:11px; color:#8aa0b5; margin-top:4px; }
.field-row { display:flex; gap:12px; }
.field-row .field { flex:1; }
.actions { display:flex; gap:8px; margin-top:16px; }
.loading { text-align:center; padding:40px; color:#8aa0b5; }
.toggle { display:flex; align-items:center; gap:8px; cursor:pointer; }
.toggle input { width:auto; }
</style>
<div class="container">
<div class="panel">
<div class="panel-title">Reglas de Recomendacion</div>
<div class="toolbar">
<input type="text" id="search" placeholder="Buscar regla..." style="flex:1" />
<button id="newBtn">+ Nueva</button>
</div>
<div class="list" id="list">
<div class="loading">Cargando...</div>
</div>
</div>
<div class="panel">
<div class="panel-title" id="formTitle">Detalle</div>
<div class="form" id="form">
<div class="form-empty">Seleccioná una regla o creá una nueva</div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("search").oninput = (e) => {
this.searchQuery = e.target.value;
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => this.load(), 300);
};
this.shadowRoot.getElementById("newBtn").onclick = () => this.showCreateForm();
this.load();
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.recommendations({ q: this.searchQuery, limit: 200 });
this.items = data.items || [];
this.loading = false;
this.renderList();
} catch (e) {
console.error("Error loading recommendations:", e);
this.items = [];
this.loading = false;
this.renderList();
}
}
renderList() {
const list = this.shadowRoot.getElementById("list");
if (this.loading) {
list.innerHTML = `<div class="loading">Cargando...</div>`;
return;
}
if (!this.items.length) {
list.innerHTML = `<div class="loading">No se encontraron reglas</div>`;
return;
}
list.innerHTML = "";
for (const item of this.items) {
const el = document.createElement("div");
el.className = "item" + (this.selected?.id === item.id ? " active" : "");
const trigger = item.trigger || {};
const keywords = (trigger.keywords || []).join(", ") || "—";
const queries = (item.queries || []).slice(0, 3).join(", ");
const hasMore = (item.queries || []).length > 3;
el.innerHTML = `
<div class="item-key">
${item.rule_key}
<span class="badge ${item.active ? "active" : "inactive"}">${item.active ? "Activa" : "Inactiva"}</span>
<span class="badge priority">P: ${item.priority}</span>
</div>
<div class="item-trigger">Keywords: ${keywords}</div>
<div class="item-queries">→ ${queries}${hasMore ? "..." : ""}</div>
`;
el.onclick = () => {
this.selected = item;
this.editMode = "edit";
this.renderList();
this.renderForm();
};
list.appendChild(el);
}
}
showCreateForm() {
this.selected = null;
this.editMode = "create";
this.renderList();
this.renderForm();
}
renderForm() {
const form = this.shadowRoot.getElementById("form");
const title = this.shadowRoot.getElementById("formTitle");
if (!this.editMode) {
title.textContent = "Detalle";
form.innerHTML = `<div class="form-empty">Seleccioná una regla o creá una nueva</div>`;
return;
}
const isCreate = this.editMode === "create";
title.textContent = isCreate ? "Nueva Regla" : "Editar Regla";
const rule_key = this.selected?.rule_key || "";
const trigger = this.selected?.trigger || {};
const queries = this.selected?.queries || [];
const ask_slots = this.selected?.ask_slots || [];
const active = this.selected?.active !== false;
const priority = this.selected?.priority || 100;
// Convert arrays to comma-separated strings for display
const triggerKeywords = (trigger.keywords || []).join(", ");
const queriesText = (queries || []).join(", ");
const askSlotsText = Array.isArray(ask_slots)
? ask_slots.map(s => typeof s === "string" ? s : s?.slot || s?.keyword || "").filter(Boolean).join(", ")
: "";
form.innerHTML = `
<div class="field">
<label>Rule Key (identificador unico)</label>
<input type="text" id="ruleKeyInput" value="${rule_key}" ${isCreate ? "" : "disabled"} placeholder="ej: asado_core, alcohol_yes" />
<div class="field-hint">Sin espacios, en minusculas con guiones bajos</div>
</div>
<div class="field-row">
<div class="field">
<label>Prioridad</label>
<input type="number" id="priorityInput" value="${priority}" min="1" max="1000" />
<div class="field-hint">Mayor = primero</div>
</div>
<div class="field">
<label>Estado</label>
<label class="toggle">
<input type="checkbox" id="activeInput" ${active ? "checked" : ""} />
<span>Activa</span>
</label>
</div>
</div>
<div class="field">
<label>Trigger (palabras clave)</label>
<textarea id="triggerInput" placeholder="asado, parrilla, carne, bife...">${triggerKeywords}</textarea>
<div class="field-hint">Palabras que activan esta regla, separadas por coma</div>
</div>
<div class="field">
<label>Productos a recomendar</label>
<textarea id="queriesInput" placeholder="provoleta, chimichurri, ensalada...">${queriesText}</textarea>
<div class="field-hint">Productos a buscar cuando se activa la regla, separados por coma</div>
</div>
<div class="field">
<label>Preguntar sobre... (opcional)</label>
<textarea id="askSlotsInput" placeholder="achuras, cerdo, vino...">${askSlotsText}</textarea>
<div class="field-hint">El bot preguntara al usuario sobre estos temas de forma natural</div>
</div>
<div class="actions">
<button id="saveBtn">${isCreate ? "Crear" : "Guardar"}</button>
${!isCreate ? `<button id="deleteBtn" class="danger">Eliminar</button>` : ""}
<button id="cancelBtn" class="secondary">Cancelar</button>
</div>
`;
this.shadowRoot.getElementById("saveBtn").onclick = () => this.save();
this.shadowRoot.getElementById("cancelBtn").onclick = () => this.cancel();
if (!isCreate) {
this.shadowRoot.getElementById("deleteBtn").onclick = () => this.delete();
}
}
parseCommaSeparated(str) {
return String(str || "")
.split(",")
.map(s => s.trim().toLowerCase())
.filter(Boolean);
}
async save() {
const ruleKey = this.shadowRoot.getElementById("ruleKeyInput").value.trim().toLowerCase().replace(/\s+/g, "_");
const priority = parseInt(this.shadowRoot.getElementById("priorityInput").value, 10) || 100;
const active = this.shadowRoot.getElementById("activeInput").checked;
// Parse comma-separated values into arrays
const triggerKeywords = this.parseCommaSeparated(this.shadowRoot.getElementById("triggerInput").value);
const queries = this.parseCommaSeparated(this.shadowRoot.getElementById("queriesInput").value);
const askSlotsKeywords = this.parseCommaSeparated(this.shadowRoot.getElementById("askSlotsInput").value);
if (!ruleKey) {
alert("El rule_key es requerido");
return;
}
// Build trigger object with keywords array
const trigger = triggerKeywords.length > 0 ? { keywords: triggerKeywords } : {};
// Ask slots as simple array of keywords (LLM will formulate questions naturally)
const ask_slots = askSlotsKeywords;
const data = {
rule_key: ruleKey,
trigger,
queries,
ask_slots,
active,
priority,
};
try {
if (this.editMode === "create") {
await api.createRecommendation(data);
} else {
await api.updateRecommendation(this.selected.id, data);
}
this.editMode = null;
this.selected = null;
await this.load();
this.renderForm();
} catch (e) {
console.error("Error saving recommendation:", e);
alert("Error guardando: " + (e.message || e));
}
}
async delete() {
if (!this.selected?.id) return;
if (!confirm(`¿Eliminar la regla "${this.selected.rule_key}"?`)) return;
try {
await api.deleteRecommendation(this.selected.id);
this.editMode = null;
this.selected = null;
await this.load();
this.renderForm();
} catch (e) {
console.error("Error deleting recommendation:", e);
alert("Error eliminando: " + (e.message || e));
}
}
cancel() {
this.editMode = null;
this.selected = null;
this.renderList();
this.renderForm();
}
}
customElements.define("recommendations-crud", RecommendationsCrud);

View File

@@ -10,17 +10,18 @@ class RunTimeline extends HTMLElement {
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; margin-bottom:10px; }
:host { display:block; padding:12px; height:100%; overflow:hidden; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; height:100%; display:flex; flex-direction:column; min-height:0; box-sizing:border-box; }
.row { display:flex; gap:8px; align-items:center; }
.muted { color:#8aa0b5; font-size:12px; }
.title { font-weight:800; }
.chatlog { display:flex; flex-direction:column; gap:8px; max-height:520px; overflow:auto; padding-right:6px; margin-top:8px; }
.chatlog { display:flex; flex-direction:column; gap:0; overflow-y:auto; padding-right:6px; margin-top:8px; flex:1; min-height:0; }
/* WhatsApp-ish dark theme bubbles */
.bubble { max-width:90%; padding:8px 10px; border-radius:14px; border:1px solid #253245; font-size:13px; line-height:1.35; white-space:pre-wrap; word-break:break-word; box-shadow: 0 1px 0 rgba(0,0,0,.35); }
.bubble { max-width:90%; margin-bottom:12px; padding:8px 10px; border-radius:14px; border:1px solid #253245; font-size:13px; line-height:1.35; white-space:pre-wrap; word-break:break-word; box-shadow: 0 1px 0 rgba(0,0,0,.35); box-sizing:border-box; }
.bubble.user { align-self:flex-end; background:#0f2a1a; border-color:#1f6f43; color:#e7eef7; }
.bubble.bot { align-self:flex-start; background:#111b2a; border-color:#2a3a55; color:#e7eef7; }
.bubble.err { align-self:flex-start; background:#241214; border-color:#e74c3c; color:#ffe9ea; cursor:pointer; }
.bubble.active { outline:2px solid #1f6feb; box-shadow: 0 0 0 2px rgba(31,111,235,.25); }
.name { display:block; font-size:12px; font-weight:800; margin-bottom:4px; opacity:.95; }
.bubble.user .name { color:#cdebd8; text-align:right; }
.bubble.bot .name { color:#c7d8ee; }
@@ -62,11 +63,30 @@ class RunTimeline extends HTMLElement {
this.loadMessages();
}
});
this._unsubHighlight = on("ui:highlightMessage", ({ message_id }) => {
this.highlightMessage(message_id);
});
// Listen for inspector heights to sync bubble heights
this._unsubInspector = on("ui:inspectorLayout", ({ chat_id, items }) => {
if (!this.chatId || chat_id !== this.chatId) return;
this.applyInspectorHeights(items);
});
// Listen for optimistic messages (show bubble immediately before API response)
this._unsubOptimistic = on("message:optimistic", (msg) => {
if (!this.chatId || msg.chat_id !== this.chatId) return;
this.addOptimisticBubble(msg);
});
}
disconnectedCallback() {
this._unsubSel?.();
this._unsubRun?.();
this._unsubHighlight?.();
this._unsubInspector?.();
this._unsubOptimistic?.();
}
async loadMessages() {
@@ -122,6 +142,7 @@ class RunTimeline extends HTMLElement {
const isErr = this.isErrorMsg(m);
const bubble = document.createElement("div");
bubble.className = `bubble ${isErr ? "err" : who}`;
bubble.dataset.messageId = m.message_id;
const nameEl = document.createElement("span");
nameEl.className = "name";
@@ -146,6 +167,118 @@ class RunTimeline extends HTMLElement {
// auto-scroll
log.scrollTop = log.scrollHeight;
requestAnimationFrame(() => this.emitLayout());
this.bindScroll(log);
}
bindScroll(log) {
if (this._scrollBound) return;
this._scrollBound = true;
log.addEventListener("scroll", () => {
emit("ui:chatScroll", { chat_id: this.chatId, scrollTop: log.scrollTop });
});
}
emitLayout() {
const log = this.shadowRoot.getElementById("log");
const box = this.shadowRoot.querySelector(".box");
const bubbles = [...log.querySelectorAll(".bubble")];
const items = bubbles.map((el) => {
const styles = window.getComputedStyle(el);
const marginBottom = parseInt(styles.marginBottom || "0", 10) || 0;
return {
message_id: el.dataset.messageId || null,
height: (el.offsetHeight || 0) + marginBottom,
};
});
emit("ui:bubblesLayout", { chat_id: this.chatId, items });
// #region agent log
fetch("http://127.0.0.1:7242/ingest/86c7b1cd-c414-4eae-852c-08e57e562b3b", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
sessionId: "debug-session",
runId: "pre-fix",
hypothesisId: "H15",
location: "run-timeline.js:180",
message: "bubbles_layout",
data: {
count: items.length,
chat_id: this.chatId || null,
scroll_height: log.scrollHeight,
client_height: log.clientHeight,
host_height: this.getBoundingClientRect().height,
box_height: box ? box.getBoundingClientRect().height : null,
},
timestamp: Date.now(),
}),
}).catch(() => {});
// #endregion
}
highlightMessage(message_id) {
const log = this.shadowRoot.getElementById("log");
if (!log) return;
const bubbles = [...log.querySelectorAll(".bubble")];
for (const el of bubbles) {
el.classList.toggle("active", el.dataset.messageId === message_id);
}
// No auto-scroll - mantener posición actual del usuario
}
applyInspectorHeights(items) {
const log = this.shadowRoot.getElementById("log");
if (!log) return;
const BUBBLE_MARGIN = 12;
const MIN_HEIGHT = 120;
const heightMap = new Map((items || []).map((it) => [it.message_id, it.height || 0]));
const bubbles = [...log.querySelectorAll(".bubble")];
for (const el of bubbles) {
const messageId = el.dataset.messageId;
const inspectorHeight = heightMap.get(messageId) || 0;
// Inspector height includes margin, extract content height
const inspectorContentHeight = Math.max(0, inspectorHeight - BUBBLE_MARGIN);
// Use max between inspector height and our minimum
const targetHeight = Math.max(inspectorContentHeight, MIN_HEIGHT);
// Always apply to ensure sync
el.style.minHeight = `${targetHeight}px`;
el.style.marginBottom = `${BUBBLE_MARGIN}px`;
}
}
addOptimisticBubble(msg) {
const log = this.shadowRoot.getElementById("log");
if (!log) return;
// Check if already exists (by optimistic ID pattern)
const existing = log.querySelector(`.bubble[data-message-id^="optimistic-"]`);
if (existing) existing.remove();
const bubble = document.createElement("div");
bubble.className = "bubble user";
bubble.dataset.messageId = msg.message_id;
const nameEl = document.createElement("span");
nameEl.className = "name";
nameEl.textContent = msg.pushName || "test_lucas";
bubble.appendChild(nameEl);
const textEl = document.createElement("div");
textEl.textContent = msg.text || "—";
bubble.appendChild(textEl);
const metaEl = document.createElement("span");
metaEl.className = "meta";
metaEl.textContent = `${new Date(msg.ts).toLocaleString()}${msg.provider} • enviando...`;
bubble.appendChild(metaEl);
log.appendChild(bubble);
log.scrollTop = log.scrollHeight;
// Emit layout update
requestAnimationFrame(() => this.emitLayout());
}
}

View File

@@ -0,0 +1,243 @@
import { api } from "../lib/api.js";
import { emit } from "../lib/bus.js";
class UsersCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.selected = null;
this.loading = false;
this.searchQuery = "";
this.shadowRoot.innerHTML = `
<style>
:host { display:block; height:100%; padding:16px; overflow:hidden; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.container { display:grid; grid-template-columns:1fr 450px; gap:16px; height:100%; }
.panel { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:16px; overflow:hidden; display:flex; flex-direction:column; }
.panel-title { font-size:14px; font-weight:700; color:#8aa0b5; text-transform:uppercase; letter-spacing:.4px; margin-bottom:12px; }
.toolbar { display:flex; gap:8px; margin-bottom:12px; }
input, select { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px 12px; font-size:13px; }
input:focus, select:focus { outline:none; border-color:#1f6feb; }
input { flex:1; }
button { cursor:pointer; background:#1f6feb; color:#fff; border:none; border-radius:8px; padding:8px 16px; font-size:13px; }
button:hover { background:#1a5fd0; }
button:disabled { opacity:.5; cursor:not-allowed; }
button.secondary { background:#253245; }
button.secondary:hover { background:#2d3e52; }
button.danger { background:#e74c3c; }
button.danger:hover { background:#c0392b; }
.list { flex:1; overflow-y:auto; }
.item { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; margin-bottom:8px; cursor:pointer; transition:all .15s; }
.item:hover { border-color:#1f6feb; }
.item.active { border-color:#1f6feb; background:#111b2a; }
.item-name { font-weight:600; color:#e7eef7; margin-bottom:4px; }
.item-meta { font-size:12px; color:#8aa0b5; }
.badge { display:inline-block; padding:2px 8px; border-radius:999px; font-size:11px; background:#253245; color:#8aa0b5; margin-left:8px; }
.badge.woo { background:#0f2a1a; color:#2ecc71; }
.detail { flex:1; overflow-y:auto; }
.detail-empty { color:#8aa0b5; text-align:center; padding:40px; }
.field { margin-bottom:16px; }
.field label { display:block; font-size:12px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.field-value { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:10px 12px; color:#e7eef7; font-size:13px; }
.actions { display:flex; gap:8px; margin-top:16px; flex-wrap:wrap; }
.loading { text-align:center; padding:40px; color:#8aa0b5; }
.stats { display:flex; gap:16px; margin-bottom:16px; }
.stat { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; flex:1; text-align:center; }
.stat-value { font-size:24px; font-weight:700; color:#1f6feb; }
.stat-label { font-size:11px; color:#8aa0b5; text-transform:uppercase; margin-top:4px; }
</style>
<div class="container">
<div class="panel">
<div class="panel-title">Usuarios</div>
<div class="stats">
<div class="stat">
<div class="stat-value" id="totalCount">—</div>
<div class="stat-label">Total</div>
</div>
<div class="stat">
<div class="stat-value" id="wooCount">—</div>
<div class="stat-label">Con Woo ID</div>
</div>
</div>
<div class="toolbar">
<input type="text" id="search" placeholder="Buscar por chat_id o nombre..." />
</div>
<div class="list" id="list">
<div class="loading">Cargando...</div>
</div>
</div>
<div class="panel">
<div class="panel-title" id="detailTitle">Detalle</div>
<div class="detail" id="detail">
<div class="detail-empty">Selecciona un usuario</div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("search").oninput = (e) => {
this.searchQuery = e.target.value;
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => this.load(), 300);
};
this.load();
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.users({ q: this.searchQuery, limit: 500 });
this.items = data.items || [];
this.loading = false;
this.renderList();
this.renderStats();
} catch (e) {
console.error("Error loading users:", e);
this.items = [];
this.loading = false;
this.renderList();
}
}
renderStats() {
const total = this.items.length;
const withWoo = this.items.filter(u => u.external_customer_id).length;
this.shadowRoot.getElementById("totalCount").textContent = total;
this.shadowRoot.getElementById("wooCount").textContent = withWoo;
}
renderList() {
const list = this.shadowRoot.getElementById("list");
if (this.loading) {
list.innerHTML = `<div class="loading">Cargando...</div>`;
return;
}
if (!this.items.length) {
list.innerHTML = `<div class="loading">No se encontraron usuarios</div>`;
return;
}
list.innerHTML = "";
for (const item of this.items) {
const el = document.createElement("div");
el.className = "item" + (this.selected?.chat_id === item.chat_id ? " active" : "");
const name = item.push_name || item.chat_id.replace(/@.+$/, "");
const wooBadge = item.external_customer_id
? `<span class="badge woo">Woo: ${item.external_customer_id}</span>`
: "";
el.innerHTML = `
<div class="item-name">${name} ${wooBadge}</div>
<div class="item-meta">${item.chat_id}</div>
`;
el.onclick = () => {
this.selected = item;
this.renderList();
this.renderDetail();
};
list.appendChild(el);
}
}
renderDetail() {
const detail = this.shadowRoot.getElementById("detail");
const title = this.shadowRoot.getElementById("detailTitle");
if (!this.selected) {
title.textContent = "Detalle";
detail.innerHTML = `<div class="detail-empty">Selecciona un usuario</div>`;
return;
}
const u = this.selected;
const name = u.push_name || u.chat_id.replace(/@.+$/, "");
title.textContent = name;
detail.innerHTML = `
<div class="field">
<label>Chat ID</label>
<div class="field-value">${u.chat_id}</div>
</div>
<div class="field">
<label>Push Name</label>
<div class="field-value">${u.push_name || "—"}</div>
</div>
<div class="field">
<label>Telefono</label>
<div class="field-value">${u.chat_id.replace(/@.+$/, "")}</div>
</div>
<div class="field">
<label>Woo Customer ID</label>
<div class="field-value">${u.external_customer_id || "Sin vincular"}</div>
</div>
<div class="field">
<label>Provider</label>
<div class="field-value">${u.provider || "—"}</div>
</div>
<div class="field">
<label>Creado</label>
<div class="field-value">${u.created_at ? new Date(u.created_at).toLocaleString() : "—"}</div>
</div>
<div class="field">
<label>Actualizado</label>
<div class="field-value">${u.updated_at ? new Date(u.updated_at).toLocaleString() : "—"}</div>
</div>
<div class="actions">
<button id="openChat">Ver Chat</button>
<button id="deleteConv" class="secondary">Borrar Chat</button>
<button id="deleteUser" class="danger">Borrar Usuario + Woo</button>
</div>
`;
detail.scrollTop = 0;
this.shadowRoot.getElementById("openChat").onclick = () => {
emit("ui:selectedChat", { chat_id: u.chat_id });
emit("ui:switchView", { view: "chat" });
};
this.shadowRoot.getElementById("deleteConv").onclick = async () => {
if (!confirm(`¿Eliminar la conversacion de "${u.chat_id}"?`)) return;
try {
await api.deleteConversation(u.chat_id);
alert("Conversacion eliminada");
} catch (e) {
alert("Error: " + (e.message || e));
}
};
this.shadowRoot.getElementById("deleteUser").onclick = async () => {
if (!confirm(`¿Eliminar usuario "${u.chat_id}", su conversacion y el customer en Woo?`)) return;
try {
await api.deleteUser(u.chat_id, { deleteWoo: true });
this.selected = null;
await this.load();
this.renderDetail();
} catch (e) {
alert("Error: " + (e.message || e));
}
};
}
}
customElements.define("users-crud", UsersCrud);