mejoras varias en frontend, separacion de intent y state, pick de articulos

This commit is contained in:
Lucas Tettamanti
2026-01-06 15:50:02 -03:00
parent dab52492b4
commit 8bb21b4edb
17 changed files with 1826 additions and 209 deletions

View File

@@ -5,6 +5,8 @@ class ChatSimulator extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this._lastPayload = null;
this._sending = false;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
@@ -15,12 +17,8 @@ class ChatSimulator extends HTMLElement {
textarea { width:100%; min-height:70px; resize:vertical; }
button { cursor:pointer; }
button.primary { background:#1f6feb; border-color:#1f6feb; }
.chatlog { display:flex; flex-direction:column; gap:8px; max-height:280px; overflow:auto; padding-right:6px; margin-top:8px; }
/* WhatsApp-ish dark theme bubbles */
.msg { 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); }
.msg.user { align-self:flex-end; background:#0f2a1a; border-color:#1f6f43; color:#e7eef7; }
.msg.bot { align-self:flex-start; background:#111b2a; border-color:#2a3a55; color:#e7eef7; }
pre { white-space:pre-wrap; word-break:break-word; background:#0f1520; border:1px solid #253245; border-radius:10px; padding:10px; margin:0; font-size:12px; color:#d7e2ef; }
button:disabled { opacity:.6; cursor:not-allowed; }
.status { margin-top:8px; font-size:12px; color:#8aa0b5; }
</style>
<div class="box">
@@ -35,19 +33,15 @@ class ChatSimulator extends HTMLElement {
<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="SimUser" placeholder="pushName (opcional)" />
<input id="pushName" style="flex:1" value="test_lucas" placeholder="pushName (opcional)" />
</div>
<div class="muted" style="margin-top:8px">Chat</div>
<div class="chatlog" id="log"></div>
<textarea id="evoText" placeholder="Texto a enviar por Evolution…"></textarea>
<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>
<div class="box">
<div class="muted">Última respuesta (raw)</div>
<pre id="raw">—</pre>
<div class="status" id="status">—</div>
</div>
`;
}
@@ -59,8 +53,54 @@ class ChatSimulator extends HTMLElement {
const evoPushEl = this.shadowRoot.getElementById("pushName");
const evoTextEl = this.shadowRoot.getElementById("evoText");
const sendEvoEl = this.shadowRoot.getElementById("sendEvo");
const retryEl = this.shadowRoot.getElementById("retry");
const statusEl = this.shadowRoot.getElementById("status");
const sendAction = async () => {
const genId = () =>
(self.crypto?.randomUUID?.() || `${Date.now()}${Math.random()}`)
.replace(/-/g, "")
.slice(0, 22)
.toUpperCase();
const buildPayload = ({ text, from, to, instance, pushName }) => {
const nowSec = Math.floor(Date.now() / 1000);
return {
body: {
event: "messages.upsert",
instance,
data: {
key: {
remoteJid: from,
fromMe: false,
id: genId(),
participant: "",
addressingMode: "pn",
},
pushName: pushName || "test_lucas",
status: "DELIVERY_ACK",
message: { conversation: text },
messageType: "conversation",
messageTimestamp: nowSec,
instanceId: genId(),
source: "sim",
to,
},
date_time: new Date().toISOString(),
sender: from,
server_url: "http://localhost",
apikey: "SIM",
},
};
};
const setSending = (v) => {
this._sending = Boolean(v);
sendEvoEl.disabled = this._sending;
retryEl.disabled = this._sending;
statusEl.textContent = this._sending ? "Enviando…" : "—";
};
const sendAction = async ({ payloadOverride = null } = {}) => {
const instance = evoInstanceEl.value.trim() || "Piaf";
const from = evoFromEl.value.trim() || "5491133230322@s.whatsapp.net"; // cliente
const to = evoToEl.value.trim() || "5491137887040@s.whatsapp.net"; // canal/destino
@@ -72,57 +112,53 @@ class ChatSimulator extends HTMLElement {
return;
}
const nowSec = Math.floor(Date.now() / 1000);
const genId = () =>
(self.crypto?.randomUUID?.() || `${Date.now()}${Math.random()}`)
.replace(/-/g, "")
.slice(0, 22)
.toUpperCase();
const payload = {
body: {
event: "messages.upsert",
instance,
data: {
key: {
// remoteJid debe ser el cliente (buyer)
remoteJid: from,
fromMe: false,
id: genId(),
participant: "",
addressingMode: "pn",
},
pushName: pushName || "SimUser",
status: "DELIVERY_ACK",
message: { conversation: text },
messageType: "conversation",
messageTimestamp: nowSec,
instanceId: genId(),
source: "sim",
},
date_time: new Date().toISOString(),
sender: from,
server_url: "http://localhost",
apikey: "SIM",
},
};
const data = await api.simEvolution(payload);
this.shadowRoot.getElementById("raw").textContent = JSON.stringify(data, null, 2);
console.log("[evolution sim] webhook response:", data);
if (!data.ok) {
this.append("bot", "Error en Evolution Sim.");
return;
}
// Optimistic: que aparezca en la columna izquierda al instante
emit("conversation:upsert", {
chat_id: from,
from: pushName || "test_lucas",
state: "IDLE",
intent: "other",
status: "ok",
last_activity: new Date().toISOString(),
last_run_id: null,
});
emit("ui:selectedChat", { chat_id: from });
this.append("user", text);
this.append("bot", `[Evolution] enviado (sim): ${text}`);
evoTextEl.value = "";
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() } } } };
setSending(true);
try {
const data = await api.simEvolution(payload);
console.log("[evolution sim] webhook response:", data);
if (!data.ok) {
statusEl.textContent = "Error enviando (ver consola)";
return;
}
evoTextEl.value = "";
evoTextEl.focus();
} catch (e) {
statusEl.textContent = `Error: ${String(e?.message || e)}`;
} finally {
setSending(false);
}
};
sendEvoEl.onclick = sendAction;
retryEl.onclick = () => {
const chat_id = evoFromEl.value.trim() || "5491133230322@s.whatsapp.net";
setSending(true);
api
.retryLast(chat_id)
.then((r) => {
if (!r?.ok) statusEl.textContent = `Retry error: ${r?.error || "unknown"}`;
else statusEl.textContent = "Retry enviado.";
})
.catch((e) => (statusEl.textContent = `Retry error: ${String(e?.message || e)}`))
.finally(() => setSending(false));
};
retryEl.disabled = false;
evoTextEl.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
@@ -144,12 +180,8 @@ class ChatSimulator extends HTMLElement {
}
append(who, text) {
const log = this.shadowRoot.getElementById("log");
const el = document.createElement("div");
el.className = "msg " + (who === "user" ? "user" : "bot");
el.textContent = text;
log.appendChild(el);
log.scrollTop = log.scrollHeight;
void who;
void text;
}
}