import { api } from "../lib/api.js"; const DAYS = [ { id: "lun", label: "Lunes", short: "Lun" }, { id: "mar", label: "Martes", short: "Mar" }, { id: "mie", label: "Miércoles", short: "Mié" }, { id: "jue", label: "Jueves", short: "Jue" }, { id: "vie", label: "Viernes", short: "Vie" }, { id: "sab", label: "Sábado", short: "Sáb" }, { id: "dom", label: "Domingo", short: "Dom" }, ]; class SettingsCrud extends HTMLElement { constructor() { super(); this.attachShadow({ mode: "open" }); this.settings = null; this.loading = false; this.saving = false; this.shadowRoot.innerHTML = `
Cargando configuración...
`; } connectedCallback() { this.load(); } async load() { this.loading = true; this.render(); try { this.settings = await api.getSettings(); // Asegurar que schedule existe if (!this.settings.schedule) { this.settings.schedule = { delivery: {}, pickup: {} }; } this.loading = false; this.render(); } catch (e) { console.error("Error loading settings:", e); this.loading = false; this.showError("Error cargando configuración: " + e.message); } } getScheduleSlot(type, dayId) { return this.settings?.schedule?.[type]?.[dayId] || null; } setScheduleSlot(type, dayId, slot) { if (!this.settings.schedule) { this.settings.schedule = { delivery: {}, pickup: {} }; } if (!this.settings.schedule[type]) { this.settings.schedule[type] = {}; } this.settings.schedule[type][dayId] = slot; } renderScheduleGrid(type, enabled) { const defaultStart = type === "delivery" ? "09:00" : "08:00"; const defaultEnd = type === "delivery" ? "18:00" : "20:00"; return DAYS.map(day => { const slot = this.getScheduleSlot(type, day.id); const isActive = slot !== null && slot !== undefined; const start = slot?.start || defaultStart; const end = slot?.end || defaultEnd; return `
${day.label}
a
`; }).join(""); } render() { const content = this.shadowRoot.getElementById("content"); if (this.loading) { content.innerHTML = `
Cargando configuración...
`; return; } if (!this.settings) { content.innerHTML = `
No se pudo cargar la configuración
`; return; } const s = this.settings; content.innerHTML = `
Información del Negocio
Se usa en los mensajes del bot
El asistente virtual
Delivery (Envío a domicilio)
Delivery habilitado
${this.renderScheduleGrid("delivery", s.delivery_enabled)}
Retiro en Tienda
Retiro en tienda habilitado
${this.renderScheduleGrid("pickup", s.pickup_enabled)}
`; this.setupEventListeners(); } setupEventListeners() { // Toggle delivery const deliveryToggle = this.shadowRoot.getElementById("deliveryToggle"); deliveryToggle?.addEventListener("click", () => { this.settings.delivery_enabled = !this.settings.delivery_enabled; this.render(); }); // Toggle pickup const pickupToggle = this.shadowRoot.getElementById("pickupToggle"); pickupToggle?.addEventListener("click", () => { this.settings.pickup_enabled = !this.settings.pickup_enabled; this.render(); }); // Day toggles this.shadowRoot.querySelectorAll(".day-toggle").forEach(toggle => { toggle.addEventListener("click", () => { const type = toggle.dataset.type; const day = toggle.dataset.day; const currentSlot = this.getScheduleSlot(type, day); if (currentSlot) { // Desactivar día this.setScheduleSlot(type, day, null); } else { // Activar día con horarios default const defaultStart = type === "delivery" ? "09:00" : "08:00"; const defaultEnd = type === "delivery" ? "18:00" : "20:00"; this.setScheduleSlot(type, day, { start: defaultStart, end: defaultEnd }); } this.render(); }); }); // Hour inputs - update on blur this.shadowRoot.querySelectorAll(".hour-start, .hour-end").forEach(input => { input.addEventListener("blur", () => { const type = input.dataset.type; const day = input.dataset.day; const isStart = input.classList.contains("hour-start"); const slot = this.getScheduleSlot(type, day); if (!slot) return; const value = input.value.trim(); if (isStart) { slot.start = value || (type === "delivery" ? "09:00" : "08:00"); } else { slot.end = value || (type === "delivery" ? "18:00" : "20:00"); } this.setScheduleSlot(type, day, slot); }); }); // Save button this.shadowRoot.getElementById("saveBtn")?.addEventListener("click", () => this.save()); // Reset button this.shadowRoot.getElementById("resetBtn")?.addEventListener("click", () => this.load()); } collectScheduleFromInputs() { const schedule = { delivery: {}, pickup: {} }; for (const type of ["delivery", "pickup"]) { this.shadowRoot.querySelectorAll(`.hour-start[data-type="${type}"]`).forEach(input => { const day = input.dataset.day; const endInput = this.shadowRoot.querySelector(`.hour-end[data-type="${type}"][data-day="${day}"]`); const toggle = this.shadowRoot.querySelector(`.day-toggle[data-type="${type}"][data-day="${day}"]`); if (toggle?.classList.contains("active")) { schedule[type][day] = { start: input.value.trim() || (type === "delivery" ? "09:00" : "08:00"), end: endInput?.value.trim() || (type === "delivery" ? "18:00" : "20:00"), }; } }); } return schedule; } async save() { // Collect schedule from inputs const schedule = this.collectScheduleFromInputs(); const data = { store_name: this.shadowRoot.getElementById("storeName")?.value || "", bot_name: this.shadowRoot.getElementById("botName")?.value || "", store_address: this.shadowRoot.getElementById("storeAddress")?.value || "", store_phone: this.shadowRoot.getElementById("storePhone")?.value || "", delivery_enabled: this.settings.delivery_enabled, pickup_enabled: this.settings.pickup_enabled, delivery_min_order: parseFloat(this.shadowRoot.getElementById("deliveryMinOrder")?.value) || 0, schedule, }; // Update settings with form values this.settings = { ...this.settings, ...data }; this.saving = true; this.render(); try { console.log("[settings-crud] Saving:", data); const result = await api.saveSettings(data); console.log("[settings-crud] Save result:", result); if (result.ok === false) { throw new Error(result.message || result.error || "Error desconocido"); } this.settings = result.settings || data; this.saving = false; this.showSuccess(result.message || "Configuración guardada correctamente"); this.render(); } catch (e) { console.error("[settings-crud] Error saving settings:", e); this.saving = false; this.showError("Error guardando: " + (e.message || e)); this.render(); } } escapeHtml(str) { return (str || "").replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); } showSuccess(msg) { const messages = this.shadowRoot.getElementById("messages"); messages.innerHTML = `
${msg}
`; setTimeout(() => { messages.innerHTML = ""; }, 4000); } showError(msg) { const messages = this.shadowRoot.getElementById("messages"); messages.innerHTML = `
${msg}
`; setTimeout(() => { messages.innerHTML = ""; }, 5000); } } customElements.define("settings-crud", SettingsCrud);