import { api } from "../lib/api.js"; import { emit, on } from "../lib/bus.js"; import { navigateToItem } from "../lib/router.js"; import { modal } from "../lib/modal.js"; class UsersCrud extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.items = []; this.selected = null; this.loading = false; this.searchQuery = ""; this.wooFilter = false; this.shadowRoot.innerHTML = `
Usuarios
Total
Con Woo ID
Cargando...
Detalle
Selecciona un usuario
`; } connectedCallback() { this.shadowRoot.getElementById("search").oninput = (e) => { this.searchQuery = e.target.value; clearTimeout(this._searchTimer); this._searchTimer = setTimeout(() => this.load(), 300); }; // Stats click handlers this.shadowRoot.getElementById("statTotal").onclick = () => { this.wooFilter = false; this.renderList(); this.updateStatStyles(); }; this.shadowRoot.getElementById("statWoo").onclick = () => { this.wooFilter = !this.wooFilter; this.renderList(); this.updateStatStyles(); }; // Escuchar cambios de ruta para deep-linking this._unsubRouter = on("router:viewChanged", ({ view, params }) => { if (view === "users" && params.id) { this.selectUserById(params.id); } }); this.load(); } disconnectedCallback() { this._unsubRouter?.(); } updateStatStyles() { const statTotal = this.shadowRoot.getElementById("statTotal"); const statWoo = this.shadowRoot.getElementById("statWoo"); statTotal.classList.toggle("active", !this.wooFilter); statWoo.classList.toggle("active", this.wooFilter); } 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(); // Si hay un usuario pendiente de selección (deep-link), seleccionarlo if (this._pendingUserId) { const user = this.items.find(u => u.chat_id === this._pendingUserId); if (user) { this.selectUser(user, { updateUrl: false }); } this._pendingUserId = null; } } 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 = `
Cargando...
`; return; } // Filter by woo ID if filter is active const filteredItems = this.wooFilter ? this.items.filter(u => u.external_customer_id) : this.items; if (!filteredItems.length) { list.innerHTML = `
No se encontraron usuarios
`; return; } list.innerHTML = ""; for (const item of filteredItems) { 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 ? `Woo: ${item.external_customer_id}` : ""; el.innerHTML = `
${name} ${wooBadge}
${item.chat_id}
`; el.onclick = () => { this.selectUser(item); }; list.appendChild(el); } } selectUser(user, { updateUrl = true } = {}) { this.selected = user; this.renderList(); this.renderDetail(); // Actualizar URL (usar chat_id codificado) if (updateUrl && user) { navigateToItem("users", user.chat_id); } } selectUserById(chatId) { if (!chatId) return; // Decodificar el chat_id de la URL const decodedId = decodeURIComponent(chatId); // Buscar en los items cargados const user = this.items.find(u => u.chat_id === decodedId); if (user) { this.selectUser(user, { updateUrl: false }); } else { // Guardar el ID pendiente para seleccionar después de cargar this._pendingUserId = decodedId; } } renderDetail() { const detail = this.shadowRoot.getElementById("detail"); const title = this.shadowRoot.getElementById("detailTitle"); if (!this.selected) { title.textContent = "Detalle"; detail.innerHTML = `
Selecciona un usuario
`; return; } const u = this.selected; const name = u.push_name || u.chat_id.replace(/@.+$/, ""); title.textContent = name; detail.innerHTML = `
${u.chat_id}
${u.push_name || "—"}
${u.chat_id.replace(/@.+$/, "")}
${u.external_customer_id || "Sin vincular"}
${u.provider || "—"}
${u.created_at ? new Date(u.created_at).toLocaleString() : "—"}
${u.updated_at ? new Date(u.updated_at).toLocaleString() : "—"}
`; 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 () => { const confirmed = await modal.confirm(`¿Eliminar la conversación de "${u.chat_id}"?`); if (!confirmed) return; try { await api.deleteConversation(u.chat_id); modal.success("Conversación eliminada"); } catch (e) { modal.error("Error: " + (e.message || e)); } }; this.shadowRoot.getElementById("deleteUser").onclick = async () => { const confirmed = await modal.confirm(`¿Eliminar usuario "${u.chat_id}", su conversación y el customer en Woo?`); if (!confirmed) return; try { await api.deleteUser(u.chat_id, { deleteWoo: true }); this.selected = null; await this.load(); this.renderDetail(); } catch (e) { modal.error("Error: " + (e.message || e)); } }; } } customElements.define("users-crud", UsersCrud);