import { api } from "../lib/api.js"; // Datos aleatorios para generar usuarios de prueba const NOMBRES = ["Juan", "María", "Carlos", "Ana", "Pedro", "Laura", "Diego", "Sofía"]; const APELLIDOS = ["García", "Rodríguez", "Martínez", "López", "González", "Fernández", "Pérez"]; const CALLES = ["Av. Corrientes", "Av. Santa Fe", "Calle Florida", "Av. Rivadavia", "Av. Cabildo", "Av. Libertador"]; function randomItem(arr) { return arr[Math.floor(Math.random() * arr.length)]; } function randomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function generateTestUser() { const randomPhone = `549${randomInt(1000000000, 9999999999)}`; const wa_chat_id = `${randomPhone}@s.whatsapp.net`; const nombre = randomItem(NOMBRES); const apellido = randomItem(APELLIDOS); return { wa_chat_id, phone: randomPhone, name: `${nombre} ${apellido}`, address: { first_name: nombre, last_name: apellido, address_1: `${randomItem(CALLES)} ${randomInt(100, 9000)}`, city: "CABA", state: "Buenos Aires", postcode: `${randomInt(1000, 1999)}`, country: "AR", phone: randomPhone, email: `${randomPhone}@no-email.local`, }, }; } class TestPanel extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.products = []; this.selectedProducts = []; this.testUser = null; this.lastOrder = null; this.lastPaymentLink = null; this.loading = false; this.shadowRoot.innerHTML = `
1. Generar Orden de Prueba
Productos seleccionados
Click "Generar Orden Aleatoria" para comenzar
Datos del usuario
2. Link de Pago (MercadoPago)
Monto
3. Simular Pago Exitoso

Simula el webhook de MercadoPago con status "approved". Esto actualiza la orden en WooCommerce a "processing".

`; } connectedCallback() { this.shadowRoot.getElementById("btnGenerate").onclick = () => this.generateRandomOrder(); this.shadowRoot.getElementById("btnClear").onclick = () => this.clearAll(); this.shadowRoot.getElementById("btnCreateOrder").onclick = () => this.createOrder(); this.shadowRoot.getElementById("btnPaymentLink").onclick = () => this.createPaymentLink(); this.shadowRoot.getElementById("btnSimulateWebhook").onclick = () => this.simulateWebhook(); this.loadProducts(); } async loadProducts() { try { const result = await api.getProductsWithStock(); this.products = result.items || []; console.log(`[test-panel] Loaded ${this.products.length} products with stock`); } catch (e) { console.error("[test-panel] Error loading products:", e); } } async generateRandomOrder() { if (this.products.length === 0) { await this.loadProducts(); } if (this.products.length === 0) { alert("No hay productos con stock disponible"); return; } // Generar usuario aleatorio this.testUser = generateTestUser(); // Seleccionar 1-3 productos aleatorios const numProducts = randomInt(1, Math.min(3, this.products.length)); const shuffled = [...this.products].sort(() => Math.random() - 0.5); this.selectedProducts = []; for (let i = 0; i < numProducts; i++) { const product = shuffled[i]; const isKg = product.sell_unit === "kg"; const quantity = isKg ? randomInt(200, 2000) : randomInt(1, 5); this.selectedProducts.push({ product_id: product.woo_product_id, name: product.name, quantity, unit: isKg ? "kg" : "unit", price: product.price, }); } this.renderProductList(); this.renderUserInfo(); this.updateButtonStates(); } renderProductList() { const container = this.shadowRoot.getElementById("productList"); if (this.selectedProducts.length === 0) { container.innerHTML = `
Click "Generar Orden Aleatoria" para comenzar
`; return; } container.innerHTML = this.selectedProducts.map((p, i) => `
${p.name}
${p.unit === "kg" ? `${p.quantity}g` : `${p.quantity}u`}
$${Number(p.price || 0).toFixed(0)}
`).join(""); container.querySelectorAll(".remove-btn").forEach(btn => { btn.onclick = (e) => { const idx = parseInt(e.target.dataset.index); this.selectedProducts.splice(idx, 1); this.renderProductList(); this.updateButtonStates(); }; }); } renderUserInfo() { const container = this.shadowRoot.getElementById("userInfo"); if (!this.testUser) { container.innerHTML = `
Se generarán automáticamente
`; return; } const addr = this.testUser.address; container.innerHTML = `
Nombre: ${addr.first_name} ${addr.last_name}
Dirección: ${addr.address_1}
Ciudad: ${addr.city}, ${addr.state}
Teléfono: ${addr.phone}
Email: ${addr.email}
`; } updateButtonStates() { const hasProducts = this.selectedProducts.length > 0; const hasOrder = this.lastOrder?.woo_order_id; const hasPaymentLink = this.lastPaymentLink?.init_point; this.shadowRoot.getElementById("btnCreateOrder").disabled = !hasProducts; this.shadowRoot.getElementById("btnPaymentLink").disabled = !hasOrder; this.shadowRoot.getElementById("btnSimulateWebhook").disabled = !hasOrder; if (hasOrder) { this.shadowRoot.getElementById("inputAmount").value = this.lastOrder.total || ""; } } async createOrder() { if (this.loading) return; this.loading = true; const btn = this.shadowRoot.getElementById("btnCreateOrder"); btn.disabled = true; btn.textContent = "Creando..."; try { const basket = { items: this.selectedProducts.map(p => ({ product_id: p.product_id, quantity: p.quantity, unit: p.unit, })), }; const result = await api.createTestOrder({ basket, address: this.testUser?.address || null, wa_chat_id: this.testUser?.wa_chat_id || null, }); if (result.ok) { this.lastOrder = result; this.shadowRoot.getElementById("orderIdValue").textContent = `#${result.woo_order_id}`; this.shadowRoot.getElementById("orderTotalValue").textContent = `$${Number(result.total || 0).toFixed(2)}`; this.shadowRoot.getElementById("orderResult").style.display = "block"; this.shadowRoot.getElementById("inputAmount").value = result.total || ""; } else { alert("Error: " + (result.error || "Error desconocido")); } } catch (e) { console.error("[test-panel] createOrder error:", e); alert("Error creando orden: " + e.message); } finally { this.loading = false; btn.textContent = "Crear Orden en WooCommerce"; this.updateButtonStates(); } } async createPaymentLink() { if (this.loading) return; if (!this.lastOrder?.woo_order_id) { alert("Primero creá una orden"); return; } const amount = parseFloat(this.shadowRoot.getElementById("inputAmount").value); if (!amount || amount <= 0) { alert("Ingresá un monto válido"); return; } this.loading = true; const btn = this.shadowRoot.getElementById("btnPaymentLink"); btn.disabled = true; btn.textContent = "Generando..."; try { const result = await api.createPaymentLink({ woo_order_id: this.lastOrder.woo_order_id, amount, }); if (result.ok) { this.lastPaymentLink = result; const linkEl = this.shadowRoot.getElementById("paymentLinkValue"); linkEl.href = result.init_point || result.sandbox_init_point || "#"; linkEl.textContent = result.init_point || result.sandbox_init_point || "—"; this.shadowRoot.getElementById("preferenceIdValue").textContent = result.preference_id || "—"; this.shadowRoot.getElementById("paymentResult").style.display = "block"; } else { alert("Error: " + (result.error || "Error desconocido")); } } catch (e) { console.error("[test-panel] createPaymentLink error:", e); alert("Error generando link: " + e.message); } finally { this.loading = false; btn.textContent = "Generar Link de Pago"; this.updateButtonStates(); } } async simulateWebhook() { if (this.loading) return; if (!this.lastOrder?.woo_order_id) { alert("Primero creá una orden"); return; } this.loading = true; const btn = this.shadowRoot.getElementById("btnSimulateWebhook"); btn.disabled = true; btn.textContent = "Simulando..."; try { const amount = parseFloat(this.shadowRoot.getElementById("inputAmount").value) || this.lastOrder.total || 0; const result = await api.simulateMpWebhook({ woo_order_id: this.lastOrder.woo_order_id, amount, }); if (result.ok) { this.shadowRoot.getElementById("webhookStatusValue").textContent = `Payment ${result.payment_id} - ${result.status}`; this.shadowRoot.getElementById("webhookOrderStatusValue").textContent = result.order_status || "processing"; this.shadowRoot.getElementById("webhookResult").style.display = "block"; } else { alert("Error: " + (result.error || "Error desconocido")); } } catch (e) { console.error("[test-panel] simulateWebhook error:", e); alert("Error simulando webhook: " + e.message); } finally { this.loading = false; btn.textContent = "Simular Pago Exitoso"; this.updateButtonStates(); } } clearAll() { this.selectedProducts = []; this.testUser = null; this.lastOrder = null; this.lastPaymentLink = null; this.renderProductList(); this.renderUserInfo(); this.updateButtonStates(); this.shadowRoot.getElementById("orderResult").style.display = "none"; this.shadowRoot.getElementById("paymentResult").style.display = "none"; this.shadowRoot.getElementById("webhookResult").style.display = "none"; this.shadowRoot.getElementById("inputAmount").value = ""; } } customElements.define("test-panel", TestPanel);