- Rediseño de la vista Chat: lista de conversaciones a la izquierda,
burbujas al centro, inspector+simulador apilados a la derecha
- chat-simulator pasa a layout vertical con config 2×2 más compacto
- Fix: construir base URL con /wp-json/{api_version} en los tres
clientes Woo (wooSnapshot, wooOrders, woo.js) — antes llamaba a
/products en vez de /wp-json/wc/v3/products
- Fix: syncFromWoo y syncProducts usan safeFetch (con credentials)
en vez de fetch directo, evitando 401/404 por cookie de sesión faltante
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
239 lines
8.7 KiB
JavaScript
239 lines
8.7 KiB
JavaScript
import { api } from "../lib/api.js";
|
|
import { emit, on } from "../lib/bus.js";
|
|
import { modal } from "../lib/modal.js";
|
|
import { toast } from "../lib/toast.js";
|
|
|
|
class ChatSimulator extends HTMLElement {
|
|
constructor() {
|
|
super();
|
|
this.attachShadow({ mode: "open" });
|
|
this._lastPayload = null;
|
|
this._sending = false;
|
|
this.shadowRoot.innerHTML = `
|
|
<style>
|
|
:host { display:block; font-family: var(--font-sans); background: var(--panel); }
|
|
* { box-sizing:border-box; }
|
|
.container { display:flex; flex-direction:column; padding: var(--space-3) var(--space-4); gap: var(--space-3); }
|
|
.section-label { color: var(--text-muted); font-size: var(--fs-xs); text-transform:uppercase; letter-spacing:0.06em; font-weight: var(--fw-semibold); margin-bottom: 6px; }
|
|
.fields-grid { display:grid; grid-template-columns:1fr 1fr; gap: 6px; }
|
|
.field { display:flex; flex-direction:column; min-width:0; }
|
|
.field label { font-size: var(--fs-xs); color: var(--text-muted); margin-bottom: 3px; font-weight: var(--fw-medium); }
|
|
input, textarea, button {
|
|
background: var(--panel);
|
|
color: var(--text);
|
|
border: 1px solid var(--border-hi);
|
|
border-radius: var(--r-md);
|
|
padding: 6px 10px;
|
|
font: 400 var(--fs-sm)/1.4 var(--font-sans);
|
|
transition: border-color .15s, box-shadow .15s;
|
|
}
|
|
input:focus, textarea:focus { outline:none; border-color: var(--accent); box-shadow: var(--focus-ring); }
|
|
input { width:100%; min-width:0; }
|
|
textarea {
|
|
width:100%; resize:none; height:72px;
|
|
word-break:break-word; overflow-wrap:anywhere;
|
|
font-family: var(--font-mono); font-size: var(--fs-sm);
|
|
}
|
|
button { cursor:pointer; white-space:nowrap; font-weight: var(--fw-medium); }
|
|
button:hover:not(:disabled) { border-color: var(--accent); background: var(--accent-soft); color: var(--accent-hover); }
|
|
button.primary { background: var(--accent); border-color: var(--accent); color: var(--text-on-acc); }
|
|
button.primary:hover:not(:disabled) { background: var(--accent-hover); border-color: var(--accent-hover); color: var(--text-on-acc); }
|
|
button:disabled { opacity:.5; cursor:not-allowed; }
|
|
.msg-row { display:flex; gap: var(--space-2); align-items:flex-end; }
|
|
.msg-row textarea { flex:1; }
|
|
.btn-col { display:flex; flex-direction:column; gap: 6px; }
|
|
.status { font-size: var(--fs-xs); color: var(--text-muted); word-break:break-word; }
|
|
</style>
|
|
|
|
<div class="container">
|
|
<div>
|
|
<div class="section-label">Evolution Sim</div>
|
|
<div class="fields-grid">
|
|
<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>
|
|
<div class="section-label">Mensaje</div>
|
|
<div class="msg-row">
|
|
<textarea id="evoText" placeholder="Texto a enviar... (Enter para enviar)"></textarea>
|
|
<div class="btn-col">
|
|
<button class="primary" id="sendEvo">Send</button>
|
|
<button id="retry">Retry</button>
|
|
</div>
|
|
</div>
|
|
<div class="status" id="status">—</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
connectedCallback() {
|
|
const evoInstanceEl = this.shadowRoot.getElementById("instance");
|
|
const evoFromEl = this.shadowRoot.getElementById("evoFrom");
|
|
const evoToEl = this.shadowRoot.getElementById("evoTo");
|
|
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 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
|
|
const text = evoTextEl.value.trim();
|
|
const pushName = evoPushEl.value.trim();
|
|
|
|
if (!from || !text) {
|
|
modal.warn("Falta from o text");
|
|
return;
|
|
}
|
|
|
|
// 1. Actualizar lista de conversaciones
|
|
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,
|
|
});
|
|
|
|
// 2. Seleccionar el chat (si es el mismo, no recarga - optimizado en run-timeline)
|
|
emit("ui:selectedChat", { chat_id: from });
|
|
|
|
// 3. Mostrar burbuja optimista 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() } } } };
|
|
setSending(true);
|
|
try {
|
|
const data = await api.simEvolution(payload);
|
|
console.log("[evolution sim] webhook response:", data);
|
|
|
|
if (!data.ok) {
|
|
toast({ kind: "error", text: `Sim Evolution: ${data.error || "respuesta no-ok"}` });
|
|
return;
|
|
}
|
|
|
|
evoTextEl.value = "";
|
|
evoTextEl.focus();
|
|
} catch (e) {
|
|
// safeFetch ya disparó toast; sólo logueamos.
|
|
console.error("[chat-simulator] send error:", 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) toast({ kind: "error", text: `Retry: ${r?.error || "fallo"}` });
|
|
else toast({ kind: "ok", text: "Retry enviado." });
|
|
})
|
|
.catch((e) => console.error("[chat-simulator] retry error:", e))
|
|
.finally(() => setSending(false));
|
|
};
|
|
retryEl.disabled = false;
|
|
|
|
evoTextEl.addEventListener("keydown", (e) => {
|
|
if (e.key === "Enter" && !e.shiftKey) {
|
|
e.preventDefault();
|
|
sendAction();
|
|
}
|
|
});
|
|
|
|
this._unsub = on("conversation:upsert", (c) => {
|
|
const chat_id = evoFromEl.value.trim() || "5491133230322@s.whatsapp.net";
|
|
if (c.chat_id === chat_id) {
|
|
// placeholder: podrías reflejar estado/intent acá si querés
|
|
}
|
|
});
|
|
}
|
|
|
|
disconnectedCallback() {
|
|
this._unsub?.();
|
|
}
|
|
|
|
append(who, text) {
|
|
void who;
|
|
void text;
|
|
}
|
|
}
|
|
|
|
customElements.define("chat-simulator", ChatSimulator);
|