Files
botino/public/components/chat-simulator.js
Lucas Tettamanti 0bf26f8eb5 Restyling light pastel: tema blanco/azul/verde + Inter self-hosted
- theme.css reescrito: paleta light (sky/emerald accents, slate neutrals),
  tokens de spacing/typography/radii/shadows, @font-face Inter +
  JetBrains Mono variable woff2 self-hosted.
- ops-shell: header blanco con nav active=accent-soft + status pill pastel.
- run-timeline: bubbles emerald-100 (user) / blue-100 (bot) sobre blanco.
- home-dashboard: helpers cssVar + withAlpha, 6 charts coordinados a
  paleta pastel (--chart-blue/green/purple/orange/pink/gray).
- 8 CRUDs (users, products, orders, conversations, aliases,
  recommendations, quantities, takeovers, settings, debug) migrados
  de hex hardcoded oscuros a var(--*).
- modal.js + toast.js refactor a vars con fallbacks; modal blanco
  con shadow-lg y soft icon backgrounds.
- test-panel: aliases :host apuntan a globals en vez de override dark.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 13:56:48 -03:00

250 lines
9.3 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; height:100%; overflow:hidden; font-family: var(--font-sans); background: var(--panel); }
* { box-sizing:border-box; }
.container { display:grid; grid-template-columns:1fr 1fr; gap:0; height:100%; min-height:0; overflow:hidden; }
.col {
display:flex; flex-direction:column;
padding: var(--space-4) var(--space-5);
border-right: 1px solid var(--border);
min-width:0; min-height:0; overflow:hidden;
}
.col:last-child { border-right:none; }
.muted { color: var(--text-muted); font-size: var(--fs-xs); margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.06em; font-weight: var(--fw-semibold); }
.row { display:flex; gap: var(--space-2); align-items:center; }
input, textarea, button, select {
background: var(--panel);
color: var(--text);
border: 1px solid var(--border-hi);
border-radius: var(--r-md);
padding: 8px 12px;
font: 400 var(--fs-sm)/1.4 var(--font-sans);
box-sizing:border-box;
transition: border-color .15s, box-shadow .15s;
}
input:focus, textarea:focus, select:focus { outline: none; border-color: var(--accent); box-shadow: var(--focus-ring); }
input { width:100%; min-width:0; }
textarea {
width:100%; resize:vertical;
min-height:120px; max-height:60vh;
min-width:0; margin-bottom: var(--space-3);
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; }
.status { font-size: var(--fs-xs); color: var(--text-muted); margin-top: 8px; word-break:break-word; }
.inputs-col { display:flex; flex-direction:column; gap: 10px; flex:1; min-height:0; min-width:0; overflow-y:auto; padding-right: 4px; }
.field { display:flex; flex-direction:column; min-width:0; }
.field label { font-size: var(--fs-xs); color: var(--text-muted); margin-bottom: 4px; font-weight: var(--fw-medium); }
.msg-col { display:flex; flex-direction:column; min-width:0; min-height:0; flex:1; }
.msg-bottom { display:flex; gap: var(--space-2); align-items:center; margin-top: 8px; flex-wrap:wrap; }
</style>
<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="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>
`;
}
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);