Actualizar configuracion.html

This commit is contained in:
2026-02-22 21:28:50 +00:00
parent a7544c98be
commit f2effcf888

View File

@@ -325,7 +325,7 @@
<div class="bg-white p-8 rounded-[2rem] shadow-sm border border-slate-100 space-y-6"> <div class="bg-white p-8 rounded-[2rem] shadow-sm border border-slate-100 space-y-6">
<div class="flex items-center gap-4 border-b border-slate-100 pb-4"> <div class="flex items-center gap-4 border-b border-slate-100 pb-4">
<div class="w-12 h-12 bg-indigo-50 text-indigo-600 rounded-full flex items-center justify-center shrink-0"> <div class="w-12 h-12 bg-indigo-50 text-indigo-600 rounded-full flex items-center justify-center shrink-0">
<i data-lucide="globe" class="w-6 h-6"></i> <i data-lucide="smartphone" class="w-6 h-6"></i>
</div> </div>
<div> <div>
<h3 class="text-xl font-black text-slate-800 tracking-tight">Portal del Cliente</h3> <h3 class="text-xl font-black text-slate-800 tracking-tight">Portal del Cliente</h3>
@@ -401,7 +401,7 @@
</div> </div>
<div class="pt-4 flex justify-end"> <div class="pt-4 flex justify-end">
<button onclick="savePortalConfig()" class="bg-blue-600 hover:bg-blue-700 text-white font-black py-3 px-8 rounded-xl shadow-lg shadow-blue-500/30 transition-all uppercase tracking-widest text-xs flex items-center gap-2"> <button onclick="savePortalConfig()" id="btnSavePortal" class="bg-blue-600 hover:bg-blue-700 text-white font-black py-3 px-8 rounded-xl shadow-lg shadow-blue-500/30 transition-all uppercase tracking-widest text-xs flex items-center gap-2">
<i data-lucide="save" class="w-4 h-4"></i> Guardar Portal <i data-lucide="save" class="w-4 h-4"></i> Guardar Portal
</button> </button>
</div> </div>
@@ -431,6 +431,7 @@
<input type="text" id="color-primary-hex" class="flex-1 bg-transparent text-sm font-mono font-bold outline-none uppercase" placeholder="#2563EB"> <input type="text" id="color-primary-hex" class="flex-1 bg-transparent text-sm font-mono font-bold outline-none uppercase" placeholder="#2563EB">
</div> </div>
</div> </div>
<div> <div>
<label class="block text-xs font-black text-slate-500 uppercase tracking-widest mb-3">Color Secundario (Acentos y Badges)</label> <label class="block text-xs font-black text-slate-500 uppercase tracking-widest mb-3">Color Secundario (Acentos y Badges)</label>
<div class="flex items-center gap-4 bg-slate-50 p-3 rounded-xl border border-slate-200"> <div class="flex items-center gap-4 bg-slate-50 p-3 rounded-xl border border-slate-200">
@@ -438,6 +439,7 @@
<input type="text" id="color-secondary-hex" class="flex-1 bg-transparent text-sm font-mono font-bold outline-none uppercase" placeholder="#F59E0B"> <input type="text" id="color-secondary-hex" class="flex-1 bg-transparent text-sm font-mono font-bold outline-none uppercase" placeholder="#F59E0B">
</div> </div>
</div> </div>
<div> <div>
<label class="block text-xs font-black text-slate-500 uppercase tracking-widest mb-3">Fondo de Pantalla (App)</label> <label class="block text-xs font-black text-slate-500 uppercase tracking-widest mb-3">Fondo de Pantalla (App)</label>
<div class="flex items-center gap-4 bg-slate-50 p-3 rounded-xl border border-slate-200"> <div class="flex items-center gap-4 bg-slate-50 p-3 rounded-xl border border-slate-200">
@@ -449,27 +451,27 @@
<div class="flex flex-col items-center"> <div class="flex flex-col items-center">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4">Vista Previa en Vivo</p> <p class="text-[10px] font-black text-slate-400 uppercase tracking-widest mb-4">Vista Previa en Vivo</p>
<div id="app-preview" class="w-64 h-[400px] border-[6px] border-slate-800 rounded-[2.5rem] shadow-2xl overflow-hidden relative scale-90 origin-top bg-white"> <div id="app-preview" class="w-64 h-[400px] border-[6px] border-slate-800 rounded-[2.5rem] shadow-2xl overflow-hidden relative bg-gray-100 scale-90 origin-top">
<div id="prev-header" class="h-20 w-full p-4 text-white"> <div id="prev-header" class="h-20 w-full p-4 text-white" style="background-color: #2563eb;">
<div class="w-8 h-2 bg-white/30 rounded mb-2"></div> <div class="w-8 h-2 bg-white/30 rounded mb-2"></div>
<div class="w-20 h-4 bg-white rounded"></div> <div class="w-20 h-4 bg-white rounded"></div>
</div> </div>
<div class="p-4 grid grid-cols-2 gap-2"> <div class="p-4 grid grid-cols-2 gap-2">
<div class="h-16 bg-white rounded-xl border border-slate-200 shadow-sm flex items-center justify-center"> <div class="h-16 bg-white rounded-xl border border-slate-200 shadow-sm flex items-center justify-center">
<div id="prev-icon" class="w-6 h-6 rounded-lg"></div> <div id="prev-icon" class="w-6 h-6 rounded-lg" style="background-color: #f59e0b;"></div>
</div> </div>
<div class="h-16 bg-white rounded-xl border border-slate-200 shadow-sm"></div> <div class="h-16 bg-white rounded-xl border border-slate-200 shadow-sm"></div>
</div> </div>
<div class="absolute bottom-6 left-4 right-4"> <div class="absolute bottom-6 left-4 right-4">
<div id="prev-btn" class="h-10 w-full rounded-xl shadow-md"></div> <div id="prev-btn" class="h-10 w-full rounded-xl shadow-md" style="background-color: #2563eb;"></div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div class="pt-6 flex justify-end"> <div class="pt-6 flex justify-end">
<button onclick="saveAppConfig()" id="btnSaveApp" class="bg-blue-600 hover:bg-blue-700 text-white font-black py-4 px-10 rounded-2xl shadow-xl transition-all uppercase tracking-widest text-xs flex items-center gap-2 active:scale-95"> <button onclick="saveAppConfig()" id="btnSaveApp" class="bg-blue-600 hover:bg-blue-700 text-white font-black py-4 px-10 rounded-2xl shadow-xl shadow-blue-500/30 transition-all uppercase tracking-widest text-xs flex items-center gap-2 active:scale-95">
<i data-lucide="save" class="w-5 h-5"></i> Aplicar a la App <i data-lucide="save" class="w-5 h-5"></i> Aplicar a todos los dispositivos
</button> </button>
</div> </div>
</div> </div>
@@ -504,6 +506,7 @@
<div class="p-6"> <div class="p-6">
<input type="hidden" id="iaModalGuildId"> <input type="hidden" id="iaModalGuildId">
<label class="block text-sm font-bold text-gray-700 mb-2">Palabras Clave</label> <label class="block text-sm font-bold text-gray-700 mb-2">Palabras Clave</label>
<p class="text-xs text-gray-500 mb-3">Escribe palabras clave separadas por comas. Si el robot detecta alguna de ellas en la descripción del servicio, lo asignará a este gremio automáticamente.</p>
<textarea id="iaModalKeywords" rows="5" class="w-full border border-gray-300 rounded-xl p-3 text-sm focus:ring-2 focus:ring-purple-500 outline-none" placeholder="Ej: fuga de agua, tubería rota, grifo, desatasco..."></textarea> <textarea id="iaModalKeywords" rows="5" class="w-full border border-gray-300 rounded-xl p-3 text-sm focus:ring-2 focus:ring-purple-500 outline-none" placeholder="Ej: fuga de agua, tubería rota, grifo, desatasco..."></textarea>
</div> </div>
<div class="p-4 border-t bg-gray-50 flex justify-end gap-3"> <div class="p-4 border-t bg-gray-50 flex justify-end gap-3">
@@ -520,100 +523,17 @@
let cachedTemplates = {}; let cachedTemplates = {};
let currentTemplateType = null; let currentTemplateType = null;
let localGuilds = []; let localGuilds = [];
let globalConfigStore = null; // Almacenamiento seguro global
document.addEventListener("DOMContentLoaded", () => { document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) window.location.href = "index.html"; if (!localStorage.getItem("token")) window.location.href = "index.html";
showTab('templates'); showTab('templates');
loadTemplates(); loadTemplates();
loadWaSettings(); loadWaSettings();
loadGlobalConfig();
}); });
// ========================================== // ==========================================
// CARGA Y GUARDADO GLOBAL ANTI-ERROR 500 // LÓGICA DE NAVEGACIÓN Y TABS
// ========================================== // ==========================================
async function loadGlobalConfig() {
try {
const res = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok && data.config) {
globalConfigStore = data.config;
// Portal
document.getElementById('confCompanyName').value = globalConfigStore.full_name || "";
if (globalConfigStore.company_logo) {
document.getElementById('confLogoBase64').value = globalConfigStore.company_logo;
document.getElementById('logoPreview').innerHTML = `<img src="${globalConfigStore.company_logo}" class="w-full h-full object-contain">`;
}
if (globalConfigStore.portal_settings) {
const s = globalConfigStore.portal_settings;
if(s.m_start) document.getElementById('mStart').value = s.m_start;
if(s.m_end) document.getElementById('mEnd').value = s.m_end;
if(s.a_start) document.getElementById('aStart').value = s.a_start;
if(s.a_end) document.getElementById('aEnd').value = s.a_end;
// App Colores (Guardados DENTRO de portal_settings para no romper la BD)
if (s.app_settings) {
document.getElementById('color-primary').value = s.app_settings.primary || "#2563EB";
document.getElementById('color-primary-hex').value = s.app_settings.primary || "#2563EB";
document.getElementById('color-secondary').value = s.app_settings.secondary || "#F59E0B";
document.getElementById('color-secondary-hex').value = s.app_settings.secondary || "#F59E0B";
document.getElementById('color-bg').value = s.app_settings.bg || "#F4F7F9";
document.getElementById('color-bg-hex').value = s.app_settings.bg || "#F4F7F9";
updateAppPreview();
}
}
}
} catch (e) { console.error("Error cargando configuración", e); }
}
async function saveConfigUnified(isApp) {
if(!globalConfigStore) return showToast("Espera a que cargue la configuración", true);
const btn = document.getElementById(isApp ? 'btnSaveApp' : 'btnSavePortal');
const original = btn.innerHTML;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
lucide.createIcons();
// Construir el paquete completo siempre
const portalSettings = globalConfigStore.portal_settings || {};
portalSettings.m_start = document.getElementById('mStart').value || "09:00";
portalSettings.m_end = document.getElementById('mEnd').value || "14:00";
portalSettings.a_start = document.getElementById('aStart').value || "16:00";
portalSettings.a_end = document.getElementById('aEnd').value || "19:00";
portalSettings.app_settings = {
primary: document.getElementById('color-primary').value || "#2563EB",
secondary: document.getElementById('color-secondary').value || "#F59E0B",
bg: document.getElementById('color-bg').value || "#F4F7F9"
};
const payload = {
company_name: document.getElementById('confCompanyName').value || globalConfigStore.full_name || "Empresa",
company_logo: document.getElementById('confLogoBase64').value || globalConfigStore.company_logo || "",
portal_settings: portalSettings
};
try {
const res = await fetch(`${API_URL}/config/company`, {
method: 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(payload)
});
if (res.ok) {
showToast(isApp ? "✅ Colores de la App Actualizados" : "✅ Portal Guardado");
localStorage.setItem('app_theme', JSON.stringify(portalSettings.app_settings)); // Para la app móvil
} else {
showToast("❌ Error al guardar en el servidor", true);
}
} catch (e) { showToast("❌ Error de conexión", true); }
finally { btn.innerHTML = original; lucide.createIcons(); }
}
function savePortalConfig() { saveConfigUnified(false); }
function saveAppConfig() { saveConfigUnified(true); }
function showTab(tabId) { function showTab(tabId) {
document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden')); document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
document.getElementById(`view-${tabId}`).classList.remove('hidden'); document.getElementById(`view-${tabId}`).classList.remove('hidden');
@@ -630,85 +550,12 @@
if(tabId === 'others') { loadCompanies(); loadStatusesConfig(); } if(tabId === 'others') { loadCompanies(); loadStatusesConfig(); }
if(tabId === 'whatsapp') { checkWhatsappStatus(); } if(tabId === 'whatsapp') { checkWhatsappStatus(); }
if(tabId === 'providers') { loadProviderCredentials(); loadIaRules(); } if(tabId === 'portal') { loadPortalConfig(); }
} if(tabId === 'app-operario') { loadAppConfig(); }
if(tabId === 'providers') {
// ========================================== loadProviderCredentials();
// LÓGICA PORTAL OPERARIO (PREVIEW COLORES) loadIaRules();
// ========================================== }
['primary', 'secondary', 'bg'].forEach(type => {
const picker = document.getElementById(`color-${type}`);
const text = document.getElementById(`color-${type}-hex`);
picker.addEventListener('input', (e) => { text.value = e.target.value.toUpperCase(); updateAppPreview(); });
text.addEventListener('input', (e) => { if(/^#[0-9A-F]{6}$/i.test(e.target.value)) { picker.value = e.target.value; updateAppPreview(); } });
});
function updateAppPreview() {
const p = document.getElementById('color-primary').value;
const s = document.getElementById('color-secondary').value;
const b = document.getElementById('color-bg').value;
document.getElementById('prev-header').style.backgroundColor = p;
document.getElementById('prev-icon').style.backgroundColor = s;
document.getElementById('prev-btn').style.backgroundColor = p;
document.getElementById('app-preview').style.backgroundColor = b;
}
function encodeLogo(input) {
const file = input.files[0];
if (!file || file.size > 1024 * 1024) { alert("Máximo 1MB"); return; }
const reader = new FileReader();
reader.onload = (e) => {
document.getElementById('confLogoBase64').value = e.target.result;
document.getElementById('logoPreview').innerHTML = `<img src="${e.target.result}" class="w-full h-full object-contain">`;
};
reader.readAsDataURL(file);
}
// ==========================================
// LÓGICA WHATSAPP
// ==========================================
async function loadWaSettings() {
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const s = data.settings || {};
document.getElementById('cfg_delay').checked = s.wa_delay_enabled !== false;
document.getElementById('cfg_evt_welcome').checked = s.wa_evt_welcome || false;
document.getElementById('cfg_evt_assigned').checked = s.wa_evt_assigned || false;
document.getElementById('cfg_evt_date').checked = s.wa_evt_date || false;
document.getElementById('cfg_evt_onway').checked = s.wa_evt_onway || false;
document.getElementById('cfg_evt_finished').checked = s.wa_evt_finished || false;
document.getElementById('cfg_evt_survey').checked = s.wa_evt_survey || false;
} catch(e) {}
}
async function saveWaSettings() {
const settings = {
wa_delay_enabled: document.getElementById('cfg_delay').checked,
wa_evt_welcome: document.getElementById('cfg_evt_welcome').checked,
wa_evt_assigned: document.getElementById('cfg_evt_assigned').checked,
wa_evt_date: document.getElementById('cfg_evt_date').checked,
wa_evt_onway: document.getElementById('cfg_evt_onway').checked,
wa_evt_finished: document.getElementById('cfg_evt_finished').checked,
wa_evt_survey: document.getElementById('cfg_evt_survey').checked
};
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify(settings) });
if (res.ok) showToast("✅ Ajustes WhatsApp guardados");
} catch(e) {}
}
async function checkWhatsappStatus() {
const container = document.getElementById('waStatusContainer');
container.innerHTML = `<div class="animate-spin w-10 h-10 border-4 border-blue-200 border-t-blue-600 rounded-full mx-auto"></div>`;
try {
const res = await fetch(`${API_URL}/whatsapp/status`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.state === "open") container.innerHTML = `<div class="text-green-600 font-bold flex flex-col items-center"><i data-lucide="check-circle" class="w-12 h-12 mb-2"></i> Conectado</div>`;
else if (data.qr) container.innerHTML = `<img src="${data.qr}" class="w-48 h-48 rounded-lg shadow-sm border">`;
else container.innerHTML = `<p class="text-orange-500 font-bold">Iniciando...</p>`;
lucide.createIcons();
} catch(e) { container.innerHTML = `<p class="text-red-500 font-bold">Error servidor</p>`; }
} }
// ========================================== // ==========================================
@@ -718,26 +565,45 @@
const list = document.getElementById('iaRulesList'); const list = document.getElementById('iaRulesList');
list.innerHTML = '<p class="text-center text-sm text-gray-400 py-8"><i data-lucide="loader-2" class="w-6 h-6 animate-spin mx-auto mb-2"></i> Cargando...</p>'; list.innerHTML = '<p class="text-center text-sm text-gray-400 py-8"><i data-lucide="loader-2" class="w-6 h-6 animate-spin mx-auto mb-2"></i> Cargando...</p>';
lucide.createIcons(); lucide.createIcons();
try { try {
const resGuilds = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const resGuilds = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const dataGuilds = await resGuilds.json(); const dataGuilds = await resGuilds.json();
if (!dataGuilds.ok || dataGuilds.guilds.length === 0) { list.innerHTML = '<p class="text-center text-sm text-orange-500 py-8">Crea gremios primero.</p>'; return; }
if (!dataGuilds.ok || dataGuilds.guilds.length === 0) {
list.innerHTML = '<p class="text-center text-sm text-orange-500 py-8">No tienes gremios creados. Crea gremios en "Otras Configuraciones" primero.</p>';
return;
}
localGuilds = dataGuilds.guilds; localGuilds = dataGuilds.guilds;
list.innerHTML = ''; list.innerHTML = '';
localGuilds.forEach(g => { localGuilds.forEach(g => {
const keywords = Array.isArray(g.ia_keywords) ? g.ia_keywords : []; const keywords = Array.isArray(g.ia_keywords) ? g.ia_keywords : [];
const tagsHtml = keywords.length > 0 ? keywords.map(kw => `<span class="inline-block bg-purple-100 text-purple-700 text-[10px] font-bold px-2 py-1 rounded-md keyword-tag m-0.5 border border-purple-200">${kw}</span>`).join('') : '<span class="text-xs text-gray-400 italic">Sin reglas asignadas.</span>'; const tagsHtml = keywords.length > 0
? keywords.map(kw => `<span class="inline-block bg-purple-100 text-purple-700 text-[10px] font-bold px-2 py-1 rounded-md keyword-tag m-0.5 border border-purple-200">${kw}</span>`).join('')
: '<span class="text-xs text-gray-400 italic">Sin reglas asignadas.</span>';
const row = document.createElement('div'); const row = document.createElement('div');
row.className = "p-4 hover:bg-purple-50/30 transition-colors grid grid-cols-12 gap-4 items-center group"; row.className = "p-4 hover:bg-purple-50/30 transition-colors grid grid-cols-12 gap-4 items-center group";
row.innerHTML = ` row.innerHTML = `
<div class="col-span-3 font-bold text-gray-800 flex items-center gap-2"><i data-lucide="hammer" class="w-4 h-4 text-gray-400 group-hover:text-purple-500"></i> ${g.name}</div> <div class="col-span-3 font-bold text-gray-800 flex items-center gap-2">
<i data-lucide="hammer" class="w-4 h-4 text-gray-400 group-hover:text-purple-500 transition-colors"></i> ${g.name}
</div>
<div class="col-span-8 flex flex-wrap items-center gap-1">${tagsHtml}</div> <div class="col-span-8 flex flex-wrap items-center gap-1">${tagsHtml}</div>
<div class="col-span-1 text-center"><button onclick="openIaModal(${g.id}, '${g.name.replace(/'/g, "\\'")}')" class="text-gray-400 hover:text-purple-600 bg-white hover:bg-purple-50 border border-gray-200 hover:border-purple-200 p-2 rounded-lg transition-all shadow-sm"><i data-lucide="edit-2" class="w-4 h-4"></i></button></div> <div class="col-span-1 text-center">
<button onclick="openIaModal(${g.id}, '${g.name.replace(/'/g, "\\'")}')" class="text-gray-400 hover:text-purple-600 bg-white hover:bg-purple-50 border border-gray-200 hover:border-purple-200 p-2 rounded-lg transition-all shadow-sm">
<i data-lucide="edit-2" class="w-4 h-4"></i>
</button>
</div>
`; `;
list.appendChild(row); list.appendChild(row);
}); });
lucide.createIcons(); lucide.createIcons();
} catch (e) { list.innerHTML = '<p class="text-center text-sm text-red-500 py-8">Error cargar reglas.</p>'; } } catch (e) {
console.error("Error cargando reglas IA:", e);
list.innerHTML = '<p class="text-center text-sm text-red-500 py-8">Error al cargar las reglas de IA.</p>';
}
} }
function openIaModal(guildId, guildName) { function openIaModal(guildId, guildName) {
@@ -760,9 +626,142 @@
method: 'PUT', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, method: 'PUT', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ keywords: keywordsArray }) body: JSON.stringify({ keywords: keywordsArray })
}); });
if (res.ok) { showToast("✅ Reglas IA guardadas"); closeIaModal(); loadIaRules(); } if (res.ok) {
else { showToast("❌ Error al guardar", true); } showToast("✅ Reglas de IA guardadas correctamente.");
} catch (e) { showToast("❌ Error de conexión", true); } closeIaModal();
loadIaRules();
} else { showToast("❌ Error al guardar las reglas.", true); }
} catch (e) { showToast("❌ Error de conexión.", true); }
}
// ==========================================
// LÓGICA PORTAL OPERARIO (COLORES)
// ==========================================
['primary', 'secondary', 'bg'].forEach(type => {
const picker = document.getElementById(`color-${type}`);
const text = document.getElementById(`color-${type}-hex`);
if(picker && text) {
picker.addEventListener('input', (e) => {
text.value = e.target.value.toUpperCase();
updateAppPreview();
});
text.addEventListener('input', (e) => {
if(/^#[0-9A-F]{6}$/i.test(e.target.value)) {
picker.value = e.target.value;
updateAppPreview();
}
});
}
});
function updateAppPreview() {
const p = document.getElementById('color-primary').value;
const s = document.getElementById('color-secondary').value;
const b = document.getElementById('color-bg').value;
document.getElementById('prev-header').style.backgroundColor = p;
document.getElementById('prev-icon').style.backgroundColor = s;
document.getElementById('prev-btn').style.backgroundColor = p;
document.getElementById('app-preview').style.backgroundColor = b;
}
async function loadAppConfig() {
try {
const res = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok && data.config && data.config.app_settings) {
const s = data.config.app_settings;
document.getElementById('color-primary').value = s.primary || "#2563EB";
document.getElementById('color-primary-hex').value = s.primary || "#2563EB";
document.getElementById('color-secondary').value = s.secondary || "#F59E0B";
document.getElementById('color-secondary-hex').value = s.secondary || "#F59E0B";
document.getElementById('color-bg').value = s.bg || "#F4F7F9";
document.getElementById('color-bg-hex').value = s.bg || "#F4F7F9";
updateAppPreview();
}
} catch (e) { console.error("Error cargando colores"); }
}
async function saveAppConfig() {
const btn = document.getElementById('btnSaveApp');
const original = btn.innerHTML;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Aplicando...';
lucide.createIcons();
const settings = {
primary: document.getElementById('color-primary').value,
secondary: document.getElementById('color-secondary').value,
bg: document.getElementById('color-bg').value
};
try {
const res = await fetch(`${API_URL}/config/company`, {
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ app_settings: settings })
});
if (res.ok) {
showToast("✅ Colores de la App actualizados");
localStorage.setItem('app_theme', JSON.stringify(settings));
}
} catch (e) { showToast("Error al guardar", true); }
finally { btn.innerHTML = original; lucide.createIcons(); }
}
// ==========================================
// LÓGICA WHATSAPP
// ==========================================
async function loadWaSettings() {
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
const s = data.settings || {};
document.getElementById('cfg_delay').checked = s.wa_delay_enabled !== false;
document.getElementById('cfg_evt_welcome').checked = s.wa_evt_welcome || false;
document.getElementById('cfg_evt_assigned').checked = s.wa_evt_assigned || false;
document.getElementById('cfg_evt_date').checked = s.wa_evt_date || false;
document.getElementById('cfg_evt_onway').checked = s.wa_evt_onway || false;
document.getElementById('cfg_evt_finished').checked = s.wa_evt_finished || false;
document.getElementById('cfg_evt_survey').checked = s.wa_evt_survey || false;
} catch(e) { console.error("Error cargando ajustes WA"); }
}
async function saveWaSettings() {
const settings = {
wa_delay_enabled: document.getElementById('cfg_delay').checked,
wa_evt_welcome: document.getElementById('cfg_evt_welcome').checked,
wa_evt_assigned: document.getElementById('cfg_evt_assigned').checked,
wa_evt_date: document.getElementById('cfg_evt_date').checked,
wa_evt_onway: document.getElementById('cfg_evt_onway').checked,
wa_evt_finished: document.getElementById('cfg_evt_finished').checked,
wa_evt_survey: document.getElementById('cfg_evt_survey').checked
};
try {
const res = await fetch(`${API_URL}/whatsapp/settings`, {
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(settings)
});
if (res.ok) showToast("✅ Ajustes de WhatsApp guardados");
else showToast("❌ Error al guardar", true);
} catch(e) { showToast("❌ Error de conexión", true); }
}
async function checkWhatsappStatus() {
const container = document.getElementById('waStatusContainer');
container.innerHTML = `<div class="flex flex-col items-center animate-pulse"><div class="w-10 h-10 border-4 border-blue-200 border-t-blue-600 rounded-full animate-spin mb-4"></div><span class="text-sm font-bold text-slate-400">Verificando instancia...</span></div>`;
lucide.createIcons();
try {
const res = await fetch(`${API_URL}/whatsapp/status`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (!data.ok) throw new Error(data.error || "Error desconocido");
if (data.state === "open") {
container.innerHTML = `<div class="flex flex-col items-center"><div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4 shadow-sm border border-green-200"><i data-lucide="check" class="w-8 h-8 text-green-600"></i></div><h4 class="text-xl font-bold text-green-700">Conectado</h4><p class="text-xs text-green-600 mt-1 font-medium bg-green-50 px-2 py-1 rounded">Instancia: ${data.instanceName}</p></div>`;
} else if (data.qr) {
container.innerHTML = `<div class="flex flex-col items-center w-full"><div id="qrcode" class="bg-white p-3 border rounded-xl shadow-sm"></div><p class="text-xs text-orange-500 mt-4 font-bold animate-pulse">Esperando escaneo...</p></div>`;
if(data.qr.startsWith('data:image')) { document.getElementById('qrcode').innerHTML = `<img src="${data.qr}" class="w-48 h-48 rounded-lg">`; }
else { new QRCode(document.getElementById("qrcode"), { text: data.qr, width: 180, height: 180 }); }
} else { container.innerHTML = `<p class="text-orange-500 font-bold">Iniciando... intenta de nuevo en unos segundos.</p>`; }
} catch(e) {
container.innerHTML = `<div class="text-center text-red-500 p-4"><i data-lucide="alert-triangle" class="w-10 h-10 mx-auto mb-2 opacity-80"></i><p class="font-bold">Error de conexión</p><p class="text-xs mt-1 bg-red-50 p-2 rounded">${e.message}</p></div>`;
}
lucide.createIcons();
} }
// ========================================== // ==========================================
@@ -774,90 +773,198 @@
const data = await res.json(); const data = await res.json();
if(data.ok) { if(data.ok) {
data.templates.forEach(t => { cachedTemplates[t.type] = t.content; }); data.templates.forEach(t => { cachedTemplates[t.type] = t.content; });
if (!currentTemplateType) document.querySelector('.tpl-btn').click(); if (!currentTemplateType) { const firstBtn = document.querySelector('.tpl-btn'); if(firstBtn) firstBtn.click(); }
} }
} catch(e) {} } catch(e) { console.error("Error templates"); }
} }
function selectTemplate(type, btn) { function selectTemplate(type, btn) {
currentTemplateType = type; currentTemplateType = type;
document.querySelectorAll('.tpl-btn').forEach(b => { document.querySelectorAll('.tpl-btn').forEach(b => {
b.classList.remove('bg-blue-50', 'ring-1', 'ring-blue-200'); b.classList.remove('bg-blue-50', 'ring-1', 'ring-blue-200');
const span = b.querySelector('span'); const s = b.querySelector('span');
if (span.classList.contains('bg-blue-600')) span.classList.replace('bg-blue-600', 'bg-blue-100'), span.classList.replace('text-white', 'text-blue-600'); if(s.classList.contains('bg-blue-600')) s.classList.replace('bg-blue-600', 'bg-blue-100'), s.classList.replace('text-white', 'text-blue-600');
if (span.classList.contains('bg-orange-600')) span.classList.replace('bg-orange-600', 'bg-orange-100'), span.classList.replace('text-white', 'text-orange-600'); if(s.classList.contains('bg-orange-600')) s.classList.replace('bg-orange-600', 'bg-orange-100'), s.classList.replace('text-white', 'text-orange-600');
}); });
btn.classList.add('bg-blue-50', 'ring-1', 'ring-blue-200'); btn.classList.add('bg-blue-50', 'ring-1', 'ring-blue-200');
const activeSpan = btn.querySelector('span'); const span = btn.querySelector('span');
if (activeSpan.classList.contains('bg-blue-100')) activeSpan.classList.replace('bg-blue-100', 'bg-blue-600'), activeSpan.classList.replace('text-blue-600', 'text-white'); if (span.classList.contains('bg-blue-100')) span.classList.replace('bg-blue-100', 'bg-blue-600'), span.classList.replace('text-blue-600', 'text-white');
else if (activeSpan.classList.contains('bg-orange-100')) activeSpan.classList.replace('bg-orange-100', 'bg-orange-600'), activeSpan.classList.replace('text-orange-600', 'text-white'); else if (span.classList.contains('bg-orange-100')) span.classList.replace('bg-orange-100', 'bg-orange-600'), span.classList.replace('text-orange-600', 'text-white');
document.getElementById('editorTitle').innerText = btn.innerText.trim(); document.getElementById('editorTitle').innerText = btn.innerText.trim();
document.getElementById('tplContent').value = cachedTemplates[type] || ""; document.getElementById('tplContent').value = cachedTemplates[type] || "";
} }
function insertVar(text) { function insertVar(text) {
const textarea = document.getElementById('tplContent'); const textarea = document.getElementById('tplContent');
if (!textarea) return;
const start = textarea.selectionStart, end = textarea.selectionEnd, val = textarea.value; const start = textarea.selectionStart, end = textarea.selectionEnd, val = textarea.value;
textarea.value = val.substring(0, start) + text + val.substring(end); textarea.value = val.substring(0, start) + text + val.substring(end);
textarea.focus(); textarea.focus();
textarea.selectionStart = textarea.selectionEnd = start + text.length;
} }
async function saveTemplate() { async function saveTemplate() {
if(!currentTemplateType) { showToast("Selecciona plantilla", true); return; }
const content = document.getElementById('tplContent').value; const content = document.getElementById('tplContent').value;
await fetch(`${API_URL}/templates`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ type: currentTemplateType, content: content }) }); try {
cachedTemplates[currentTemplateType] = content; const res = await fetch(`${API_URL}/templates`, {
showToast("Guardado"); method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify({ type: currentTemplateType, content: content })
});
if(res.ok) { cachedTemplates[currentTemplateType] = content; showToast("Guardado"); } else { showToast("Error", true); }
} catch(e) { showToast("Error", true); }
} }
// ========================================== // ==========================================
// LÓGICA OTROS Y PROVEEDORES // LÓGICA OTROS (COMPAÑÍAS Y ESTADOS)
// ========================================== // ==========================================
async function loadCompanies() { async function loadCompanies() {
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const list = document.getElementById('listCompanies');
const data = await res.json(); list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>';
const list = document.getElementById('listCompanies'); list.innerHTML = ""; try {
data.companies.forEach(c => { list.innerHTML += `<div class="p-3 border border-gray-100 rounded-lg bg-gray-50 flex justify-between items-center"><span class="font-bold text-sm">${c.name}</span><button onclick="deleteCompany(${c.id})" class="text-gray-300 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button></div>`; }); const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
lucide.createIcons(); const data = await res.json();
list.innerHTML = "";
if(data.companies.length === 0) { list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-4">Sin compañías.</p>'; return; }
data.companies.forEach(c => {
const div = document.createElement('div');
div.className = "p-3 border border-gray-100 rounded-lg bg-gray-50 flex justify-between items-center group hover:border-blue-200 transition-colors";
div.innerHTML = `<span class="font-bold text-gray-700 text-sm">${c.name}</span><button onclick="deleteCompany(${c.id})" class="text-gray-300 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button>`;
list.appendChild(div);
});
lucide.createIcons();
} catch(e) { list.innerHTML = '<p class="text-red-500 text-xs text-center">Error</p>'; }
} }
async function addCompany() { async function addCompany() {
const name = document.getElementById('newCompanyInput').value; const input = document.getElementById('newCompanyInput'), name = input.value.trim();
await fetch(`${API_URL}/companies`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ name }) }); if(!name) return;
document.getElementById('newCompanyInput').value = ""; loadCompanies(); try {
const res = await fetch(`${API_URL}/companies`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ name: name }) });
if(res.ok) { showToast("Añadido"); input.value = ""; loadCompanies(); }
} catch(e) { showToast("Error", true); }
}
async function deleteCompany(id) {
if(!confirm("¿Borrar?")) return;
await fetch(`${API_URL}/companies/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
loadCompanies();
} }
async function deleteCompany(id) { if(confirm("Borrar?")) { await fetch(`${API_URL}/companies/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); loadCompanies(); } }
async function loadStatusesConfig() { async function loadStatusesConfig() {
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const list = document.getElementById('listStatuses');
const data = await res.json(); list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>';
const list = document.getElementById('listStatuses'); list.innerHTML = ""; try {
data.statuses.forEach(s => { list.innerHTML += `<div class="p-3 border border-gray-100 rounded-lg bg-gray-50 flex justify-between items-center"><div class="flex items-center gap-2"><div class="w-3 h-3 rounded-full bg-${s.color}-500"></div><span class="font-bold text-sm">${s.name}</span></div>${s.is_system ? '<i data-lucide="lock" class="w-4 h-4 text-gray-300"></i>' : `<button onclick="deleteStatus(${s.id})" class="text-gray-300 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button>`}</div>`; }); const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
lucide.createIcons(); const data = await res.json();
list.innerHTML = "";
data.statuses.forEach(s => {
const div = document.createElement('div');
div.className = "p-3 border border-gray-100 rounded-lg bg-gray-50 flex justify-between items-center group hover:border-blue-200 transition-colors";
const actionBtn = s.is_system ? `<i data-lucide="lock" class="w-4 h-4 text-slate-300" title="Estado del sistema"></i>` : `<button onclick="deleteStatus(${s.id})" class="text-gray-300 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button>`;
div.innerHTML = `<div class="flex items-center gap-3"><div class="w-3 h-3 rounded-full bg-${s.color}-500"></div><span class="font-bold text-gray-700 text-sm">${s.name}</span></div>${actionBtn}`;
list.appendChild(div);
});
lucide.createIcons();
} catch(e) { list.innerHTML = '<p class="text-red-500 text-xs text-center">Error</p>'; }
} }
async function addStatus() {
const name = document.getElementById('newStatusInput').value, color = document.getElementById('newStatusColor').value;
await fetch(`${API_URL}/statuses`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ name, color }) });
document.getElementById('newStatusInput').value = ""; loadStatusesConfig();
}
async function deleteStatus(id) { if(confirm("Borrar?")) { await fetch(`${API_URL}/statuses/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); loadStatusesConfig(); } }
async function loadProviderCredentials() { async function addStatus() {
const res = await fetch(`${API_URL}/providers/credentials`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } }); const input = document.getElementById('newStatusInput'), color = document.getElementById('newStatusColor').value, name = input.value.trim();
const data = await res.json(); if(!name) return;
data.credentials.forEach(c => { const inp = document.getElementById(`user_${c.provider.toLowerCase()}`); if(inp) inp.value = c.username; }); try {
const res = await fetch(`${API_URL}/statuses`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ name: name, color: color }) });
if(res.ok) { showToast("Añadido"); input.value = ""; loadStatusesConfig(); }
} catch(e) { showToast("Error", true); }
} }
async function saveProviderCreds(event, provider) {
event.preventDefault(); async function deleteStatus(id) {
const username = document.getElementById(`user_${provider}`).value, password = document.getElementById(`pass_${provider}`).value; if(!confirm("¿Borrar estado?")) return;
if(!username || !password) return showToast("Faltan datos", true); try {
await fetch(`${API_URL}/providers/credentials`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ provider, username, password }) }); const res = await fetch(`${API_URL}/statuses/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
showToast(`✅ Acceso a ${provider} guardado`); if(res.ok) { showToast("Estado eliminado"); loadStatusesConfig(); }
else { const j = await res.json(); showToast(j.error || "Error", true); }
} catch(e) { showToast("Error de conexión", true); }
}
// ==========================================
// LÓGICA PROVEEDORES CREDENCIALES
// ==========================================
async function loadProviderCredentials() {
try {
const res = await fetch(`${API_URL}/providers/credentials`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
data.credentials.forEach(c => {
const userInp = document.getElementById(`user_${c.provider.toLowerCase()}`);
if(userInp) userInp.value = c.username;
});
}
} catch(e) { console.error("Error creds"); }
}
// ==========================================
// LÓGICA PORTAL CLIENTE
// ==========================================
async function loadPortalConfig() {
try {
const res = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok && data.config) {
document.getElementById('confCompanyName').value = data.config.full_name || "";
if (data.config.company_logo) {
document.getElementById('confLogoBase64').value = data.config.company_logo;
document.getElementById('logoPreview').innerHTML = `<img src="${data.config.company_logo}" class="w-full h-full object-contain">`;
}
if (data.config.portal_settings) {
const s = data.config.portal_settings;
if(s.m_start) document.getElementById('mStart').value = s.m_start;
if(s.m_end) document.getElementById('mEnd').value = s.m_end;
if(s.a_start) document.getElementById('aStart').value = s.a_start;
if(s.a_end) document.getElementById('aEnd').value = s.a_end;
}
}
} catch (e) { console.error("Error portal"); }
}
function encodeLogo(input) {
const file = input.files[0];
if (!file || file.size > 1024 * 1024) { alert("Máximo 1MB"); return; }
const reader = new FileReader();
reader.onload = (e) => {
document.getElementById('confLogoBase64').value = e.target.result;
document.getElementById('logoPreview').innerHTML = `<img src="${e.target.result}" class="w-full h-full object-contain">`;
};
reader.readAsDataURL(file);
}
async function savePortalConfig() {
const btn = document.getElementById('btnSavePortal'), original = btn.innerHTML;
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
lucide.createIcons();
const payload = {
company_name: document.getElementById('confCompanyName').value,
company_logo: document.getElementById('confLogoBase64').value,
portal_settings: {
m_start: document.getElementById('mStart').value, m_end: document.getElementById('mEnd').value,
a_start: document.getElementById('aStart').value, a_end: document.getElementById('aEnd').value
}
};
try {
const res = await fetch(`${API_URL}/config/company`, {
method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(payload)
});
if (res.ok) showToast("Configuración del Portal guardada");
} catch (e) { showToast("Error conexión", true); }
finally { btn.innerHTML = original; lucide.createIcons(); }
} }
function showToast(msg, isError = false) { function showToast(msg, isError = false) {
const t = document.getElementById('toast'), m = document.getElementById('toastMsg'); const t = document.getElementById('toast'), m = document.getElementById('toastMsg');
t.className = `fixed bottom-5 right-5 px-6 py-3 rounded-lg shadow-xl transition-all duration-300 z-50 flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white font-medium opacity-100 translate-y-0`; t.className = `fixed bottom-5 right-5 px-6 py-3 rounded-lg shadow-xl transition-all duration-300 z-50 flex items-center gap-3 ${isError ? 'bg-red-600' : 'bg-slate-800'} text-white font-medium`;
m.innerText = msg; m.innerText = msg; t.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => t.className += " opacity-0 translate-y-20", 3000); setTimeout(() => t.classList.add('translate-y-20', 'opacity-0'), 3000);
} }
</script> </script>
</body> </body>