Files
botino/public/components/takeovers-crud.js
2026-01-26 01:21:08 -03:00

600 lines
22 KiB
JavaScript

import { api } from "../lib/api.js";
import { on } from "../lib/bus.js";
import { modal } from "../lib/modal.js";
class TakeoversCrud extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.items = [];
this.selected = null;
this.loading = false;
this.products = [];
this.pendingCount = 0;
this.cartItemsToAdd = []; // Items que el humano quiere agregar al carrito
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:350px 1fr; 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; display:flex; align-items:center; gap:8px; }
.panel-title .badge { background:#e74c3c; color:#fff; padding:2px 8px; border-radius:10px; font-size:11px; }
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 { resize:vertical; min-height:100px; }
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-query { font-weight:600; color:#f39c12; margin-bottom:4px; font-size:14px; }
.item-reason { font-size:12px; color:#8aa0b5; margin-bottom:4px; }
.item-time { font-size:11px; color:#6c7a89; }
.item-chat { font-size:11px; color:#1f6feb; }
.form { flex:1; overflow-y:auto; display:flex; flex-direction:column; gap:16px; }
.form-empty { color:#8aa0b5; text-align:center; padding:40px; }
.field { }
.field label { display:block; font-size:12px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; letter-spacing:.4px; }
.actions { display:flex; gap:8px; margin-top:16px; }
.loading { text-align:center; padding:40px; color:#8aa0b5; }
.conversation-history { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; max-height:200px; overflow-y:auto; }
.msg { margin-bottom:8px; padding:8px; border-radius:6px; font-size:12px; }
.msg.user { background:#1a2a3a; border-left:3px solid #1f6feb; }
.msg.assistant { background:#1a2535; border-left:3px solid #2ecc71; }
.msg-role { font-size:10px; color:#8aa0b5; margin-bottom:4px; text-transform:uppercase; }
.msg-content { color:#e7eef7; white-space:pre-wrap; }
.query-highlight { background:#f39c1230; border:1px solid #f39c12; border-radius:8px; padding:12px; margin-bottom:16px; }
.query-highlight label { color:#f39c12; }
.query-highlight .query { font-size:16px; font-weight:600; color:#f39c12; margin-top:4px; }
.alias-section { background:#0f1520; border:1px solid #253245; border-radius:8px; padding:12px; margin-top:12px; }
.alias-section h4 { margin:0 0 12px; font-size:13px; color:#8aa0b5; }
.checkbox-row { display:flex; align-items:center; gap:8px; margin-bottom:12px; }
.checkbox-row input[type="checkbox"] { width:auto; }
.checkbox-row label { font-size:13px; color:#e7eef7; text-transform:none; }
.product-selector { position:relative; }
.product-dropdown {
position:absolute; top:100%; left:0; right:0; z-index:100;
background:#0f1520; border:1px solid #253245; border-radius:8px;
max-height:200px; overflow-y:auto; display:none;
}
.product-dropdown.open { display:block; }
.product-option {
padding:8px 12px; cursor:pointer; font-size:13px; color:#e7eef7;
display:flex; justify-content:space-between; align-items:center;
}
.product-option:hover { background:#1a2535; }
.product-option .price { font-size:11px; color:#8aa0b5; }
.cart-section { background:#0d2818; border:1px solid #2ecc71; border-radius:8px; padding:12px; margin-bottom:12px; }
.cart-section h4 { margin:0 0 12px; font-size:13px; color:#2ecc71; display:flex; align-items:center; gap:8px; }
.cart-section h4 svg { width:16px; height:16px; fill:#2ecc71; }
.cart-items-list { margin-bottom:12px; }
.cart-item-row { display:flex; align-items:center; gap:8px; padding:8px; background:#0f1520; border-radius:6px; margin-bottom:6px; }
.cart-item-row .name { flex:1; font-size:13px; color:#e7eef7; }
.cart-item-row .qty { width:60px; text-align:center; }
.cart-item-row .unit-select { width:80px; }
.cart-item-row .remove-btn { background:#e74c3c; color:#fff; border:none; border-radius:4px; padding:4px 8px; cursor:pointer; font-size:11px; }
.cart-item-row .remove-btn:hover { background:#c0392b; }
.add-cart-row { display:flex; gap:8px; align-items:flex-end; }
.add-cart-row .product-selector { flex:1; }
.add-cart-row .qty-input { width:70px; }
.add-cart-row .unit-select { width:80px; }
.add-cart-row button { white-space:nowrap; }
.no-pending { text-align:center; padding:60px 20px; color:#2ecc71; }
.no-pending svg { width:48px; height:48px; fill:#2ecc71; margin-bottom:16px; }
</style>
<div class="container">
<div class="panel">
<div class="panel-title">
Takeovers Pendientes
<span class="badge" id="pendingBadge" style="display:none;">0</span>
</div>
<div class="list" id="list">
<div class="loading">Cargando...</div>
</div>
</div>
<div class="panel">
<div class="panel-title">Responder</div>
<div class="form" id="form">
<div class="form-empty">Selecciona un takeover para responder</div>
</div>
</div>
</div>
`;
}
connectedCallback() {
this.load();
this.loadProducts();
// Refresh cuando se recibe evento SSE de nuevo takeover
this._unsubSse = on("takeover:created", () => this.load());
}
disconnectedCallback() {
this._unsubSse?.();
}
async load() {
this.loading = true;
this.renderList();
try {
const data = await api.takeovers({ limit: 50 });
this.items = data.items || [];
this.pendingCount = data.pending_count || this.items.length;
this.loading = false;
this.renderList();
} catch (e) {
console.error("Error loading takeovers:", e);
this.items = [];
this.loading = false;
this.renderList();
}
}
async loadProducts() {
try {
const data = await api.products({ limit: 2000 });
this.products = data.items || [];
} catch (e) {
console.error("Error loading products:", e);
this.products = [];
}
}
getProductName(id) {
const p = this.products.find(x => x.woo_product_id === id);
return p?.name || `Producto #${id}`;
}
formatTime(dateStr) {
if (!dateStr) return "";
const d = new Date(dateStr);
const now = new Date();
const diffMs = now - d;
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return "Hace un momento";
if (diffMins < 60) return `Hace ${diffMins} min`;
if (diffMins < 1440) return `Hace ${Math.floor(diffMins / 60)} hs`;
return d.toLocaleDateString("es-AR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" });
}
renderList() {
const list = this.shadowRoot.getElementById("list");
const badge = this.shadowRoot.getElementById("pendingBadge");
if (this.pendingCount > 0) {
badge.textContent = this.pendingCount;
badge.style.display = "inline";
} else {
badge.style.display = "none";
}
if (this.loading) {
list.innerHTML = `<div class="loading">Cargando...</div>`;
return;
}
if (!this.items.length) {
list.innerHTML = `
<div class="no-pending">
<svg viewBox="0 0 24 24"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41L9 16.17z"/></svg>
<div>No hay takeovers pendientes</div>
</div>
`;
return;
}
list.innerHTML = "";
for (const item of this.items) {
const el = document.createElement("div");
el.className = "item" + (this.selected?.id === item.id ? " active" : "");
el.innerHTML = `
<div class="item-query">"${item.pending_query}"</div>
<div class="item-reason">${this.getReasonLabel(item.reason)}</div>
<div class="item-chat">Chat: ${item.chat_id}</div>
<div class="item-time">${this.formatTime(item.created_at)}</div>
`;
el.onclick = () => this.selectTakeover(item);
list.appendChild(el);
}
}
getReasonLabel(reason) {
const labels = {
product_not_found: "Producto no encontrado",
low_confidence: "Baja confianza del NLU",
ambiguous: "Consulta ambigua",
};
return labels[reason] || reason;
}
async selectTakeover(item) {
this.selected = item;
this.renderList();
// Cargar detalles con historial
try {
const details = await api.getTakeover(item.id);
this.selected = { ...item, ...details };
this.renderForm();
} catch (e) {
console.error("Error loading takeover details:", e);
this.renderForm();
}
}
renderForm() {
const form = this.shadowRoot.getElementById("form");
if (!this.selected) {
form.innerHTML = `<div class="form-empty">Selecciona un takeover para responder</div>`;
return;
}
const history = this.selected.conversation_history || this.selected.recent_messages || [];
form.innerHTML = `
<div class="query-highlight">
<label>Consulta del cliente</label>
<div class="query">"${this.selected.pending_query}"</div>
</div>
${history.length > 0 ? `
<div class="field">
<label>Historial de conversacion</label>
<div class="conversation-history">
${history.slice(-10).map(m => `
<div class="msg ${m.role}">
<div class="msg-role">${m.role === "user" ? "Cliente" : "Bot"}</div>
<div class="msg-content">${this.escapeHtml((m.content || "").slice(0, 300))}</div>
</div>
`).join("")}
</div>
</div>
` : ""}
<div class="cart-section">
<h4>
<svg viewBox="0 0 24 24"><path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.49 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/></svg>
Agregar al carrito del cliente
</h4>
<div class="cart-items-list" id="cartItemsList"></div>
<div class="add-cart-row">
<div class="product-selector" id="cartProductSelector">
<input type="text" id="cartProductSearch" placeholder="Buscar producto..." />
<div class="product-dropdown" id="cartProductDropdown"></div>
</div>
<input type="number" id="cartQtyInput" class="qty-input" placeholder="Cant" min="0.1" step="0.1" value="1" />
<select id="cartUnitSelect" class="unit-select">
<option value="kg">kg</option>
<option value="unit">unidad</option>
<option value="g">gramos</option>
</select>
<button type="button" id="addCartItemBtn" class="secondary">+ Agregar</button>
</div>
</div>
<div class="alias-section">
<h4>Agregar Alias (opcional)</h4>
<div class="checkbox-row">
<input type="checkbox" id="addAliasCheck" />
<label for="addAliasCheck">Agregar "${this.selected.pending_query}" como alias de un producto</label>
</div>
<div id="aliasProductSection" style="display:none;">
<div class="field">
<label>Seleccionar producto</label>
<div class="product-selector" id="productSelector">
<input type="text" id="productSearch" placeholder="Buscar producto..." />
<div class="product-dropdown" id="productDropdown"></div>
</div>
</div>
</div>
</div>
<div class="field" style="flex:1;">
<label>Tu respuesta (se enviara como el bot)</label>
<textarea id="responseInput" placeholder="Ej: Te anoto 2kg de vacío. ¿Algo más?"></textarea>
</div>
<div class="actions">
<button id="respondBtn">Enviar Respuesta</button>
<button id="cancelBtn" class="danger">Cancelar Takeover</button>
</div>
`;
// Event listeners
this.shadowRoot.getElementById("respondBtn").onclick = () => this.respond();
this.shadowRoot.getElementById("cancelBtn").onclick = () => this.cancel();
const addAliasCheck = this.shadowRoot.getElementById("addAliasCheck");
const aliasSection = this.shadowRoot.getElementById("aliasProductSection");
addAliasCheck.onchange = () => {
aliasSection.style.display = addAliasCheck.checked ? "block" : "none";
};
// Limpiar items al cambiar de takeover
this.cartItemsToAdd = [];
this.renderCartItemsList();
this.setupProductSelector();
this.setupCartProductSelector();
}
renderCartItemsList() {
const container = this.shadowRoot.getElementById("cartItemsList");
if (!container) return;
if (this.cartItemsToAdd.length === 0) {
container.innerHTML = `<div style="font-size:12px;color:#8aa0b5;padding:8px;">Sin items agregados</div>`;
return;
}
container.innerHTML = this.cartItemsToAdd.map((item, idx) => `
<div class="cart-item-row">
<span class="name">${item.name}</span>
<input type="number" class="qty" value="${item.qty}" min="0.1" step="0.1" data-idx="${idx}" />
<select class="unit-select" data-idx="${idx}">
<option value="kg" ${item.unit === 'kg' ? 'selected' : ''}>kg</option>
<option value="unit" ${item.unit === 'unit' ? 'selected' : ''}>unidad</option>
<option value="g" ${item.unit === 'g' ? 'selected' : ''}>gramos</option>
</select>
<button class="remove-btn" data-idx="${idx}">✕</button>
</div>
`).join("");
// Event listeners para editar/eliminar
container.querySelectorAll(".qty").forEach(input => {
input.onchange = (e) => {
const idx = parseInt(e.target.dataset.idx, 10);
this.cartItemsToAdd[idx].qty = parseFloat(e.target.value) || 1;
};
});
container.querySelectorAll(".unit-select").forEach(select => {
select.onchange = (e) => {
const idx = parseInt(e.target.dataset.idx, 10);
this.cartItemsToAdd[idx].unit = e.target.value;
};
});
container.querySelectorAll(".remove-btn").forEach(btn => {
btn.onclick = (e) => {
const idx = parseInt(e.target.dataset.idx, 10);
this.cartItemsToAdd.splice(idx, 1);
this.renderCartItemsList();
};
});
}
setupCartProductSelector() {
const searchInput = this.shadowRoot.getElementById("cartProductSearch");
const dropdown = this.shadowRoot.getElementById("cartProductDropdown");
const addBtn = this.shadowRoot.getElementById("addCartItemBtn");
const qtyInput = this.shadowRoot.getElementById("cartQtyInput");
const unitSelect = this.shadowRoot.getElementById("cartUnitSelect");
if (!searchInput || !dropdown || !addBtn) return;
let selectedProduct = null;
const renderDropdown = (query) => {
const q = (query || "").toLowerCase().trim();
let filtered = this.products;
if (q) {
filtered = filtered.filter(p => p.name.toLowerCase().includes(q));
}
filtered = filtered.slice(0, 30);
if (!filtered.length) {
dropdown.classList.remove("open");
return;
}
dropdown.innerHTML = filtered.map(p => `
<div class="product-option" data-id="${p.woo_product_id}" data-name="${this.escapeHtml(p.name)}" data-unit="${p.sell_unit || 'kg'}">
<span>${p.name}</span>
<span class="price">$${p.price || 0}</span>
</div>
`).join("");
dropdown.querySelectorAll(".product-option").forEach(opt => {
opt.onclick = () => {
selectedProduct = {
woo_id: parseInt(opt.dataset.id, 10),
name: opt.dataset.name,
};
searchInput.value = selectedProduct.name;
// Auto-seleccionar unidad según producto
const productUnit = opt.dataset.unit || "kg";
if (unitSelect) {
unitSelect.value = productUnit === "unit" || productUnit === "Unidad" ? "unit" : "kg";
}
dropdown.classList.remove("open");
};
});
dropdown.classList.add("open");
};
searchInput.oninput = () => {
selectedProduct = null;
clearTimeout(this._cartSearchTimer);
this._cartSearchTimer = setTimeout(() => renderDropdown(searchInput.value), 150);
};
searchInput.onfocus = () => renderDropdown(searchInput.value);
addBtn.onclick = () => {
if (!selectedProduct) {
modal.warn("Selecciona un producto primero");
return;
}
const qty = parseFloat(qtyInput.value) || 1;
const unit = unitSelect.value || "kg";
this.cartItemsToAdd.push({
woo_id: selectedProduct.woo_id,
name: selectedProduct.name,
qty,
unit,
});
// Limpiar inputs
searchInput.value = "";
qtyInput.value = "1";
selectedProduct = null;
this.renderCartItemsList();
};
// Close dropdown on outside click
document.addEventListener("click", (e) => {
if (!this.shadowRoot.getElementById("cartProductSelector")?.contains(e.target)) {
dropdown.classList.remove("open");
}
});
}
escapeHtml(str) {
return (str || "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
setupProductSelector() {
const searchInput = this.shadowRoot.getElementById("productSearch");
const dropdown = this.shadowRoot.getElementById("productDropdown");
if (!searchInput || !dropdown) return;
this._selectedProductId = null;
const renderDropdown = (query) => {
const q = (query || "").toLowerCase().trim();
let filtered = this.products;
if (q) {
filtered = filtered.filter(p => p.name.toLowerCase().includes(q));
}
filtered = filtered.slice(0, 30);
if (!filtered.length) {
dropdown.classList.remove("open");
return;
}
dropdown.innerHTML = filtered.map(p => `
<div class="product-option" data-id="${p.woo_product_id}">
<span>${p.name}</span>
<span class="price">$${p.price || 0}</span>
</div>
`).join("");
dropdown.querySelectorAll(".product-option").forEach(opt => {
opt.onclick = () => {
this._selectedProductId = parseInt(opt.dataset.id, 10);
searchInput.value = this.getProductName(this._selectedProductId);
dropdown.classList.remove("open");
};
});
dropdown.classList.add("open");
};
searchInput.oninput = () => {
this._selectedProductId = null;
clearTimeout(this._searchTimer);
this._searchTimer = setTimeout(() => renderDropdown(searchInput.value), 150);
};
searchInput.onfocus = () => renderDropdown(searchInput.value);
// Close on outside click
document.addEventListener("click", (e) => {
if (!this.shadowRoot.getElementById("productSelector")?.contains(e.target)) {
dropdown.classList.remove("open");
}
});
}
async respond() {
const response = this.shadowRoot.getElementById("responseInput").value.trim();
if (!response) {
modal.warn("Escribe una respuesta");
return;
}
const addAliasCheck = this.shadowRoot.getElementById("addAliasCheck");
let addAlias = null;
if (addAliasCheck.checked && this._selectedProductId) {
addAlias = {
query: this.selected.pending_query,
woo_product_id: this._selectedProductId,
};
}
// Items a agregar al carrito del cliente
const cartItems = this.cartItemsToAdd.length > 0 ? this.cartItemsToAdd : null;
try {
await api.respondTakeover(this.selected.id, {
response,
add_alias: addAlias,
cart_items: cartItems,
});
const itemsMsg = cartItems ? ` (${cartItems.length} item(s) agregados al carrito)` : "";
modal.success("Respuesta enviada" + itemsMsg);
this.selected = null;
this.cartItemsToAdd = [];
await this.load();
this.renderForm();
} catch (e) {
console.error("Error responding:", e);
modal.error("Error: " + (e.message || e));
}
}
async cancel() {
const confirmed = await modal.confirm("¿Cancelar este takeover? El cliente no recibirá respuesta automática.");
if (!confirmed) return;
try {
await api.cancelTakeover(this.selected.id);
modal.success("Takeover cancelado");
this.selected = null;
await this.load();
this.renderForm();
} catch (e) {
console.error("Error cancelling:", e);
modal.error("Error: " + (e.message || e));
}
}
}
customElements.define("takeovers-crud", TakeoversCrud);