Actualizar configuracion.html
This commit is contained in:
@@ -325,7 +325,7 @@
|
||||
<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="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>
|
||||
<h3 class="text-xl font-black text-slate-800 tracking-tight">Portal del Cliente</h3>
|
||||
@@ -401,7 +401,7 @@
|
||||
</div>
|
||||
|
||||
<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
|
||||
</button>
|
||||
</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">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<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">
|
||||
@@ -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">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<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">
|
||||
@@ -449,27 +451,27 @@
|
||||
|
||||
<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>
|
||||
<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="prev-header" class="h-20 w-full p-4 text-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" style="background-color: #2563eb;">
|
||||
<div class="w-8 h-2 bg-white/30 rounded mb-2"></div>
|
||||
<div class="w-20 h-4 bg-white rounded"></div>
|
||||
</div>
|
||||
<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 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 class="h-16 bg-white rounded-xl border border-slate-200 shadow-sm"></div>
|
||||
</div>
|
||||
<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 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">
|
||||
<i data-lucide="save" class="w-5 h-5"></i> Aplicar a la App
|
||||
<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 todos los dispositivos
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -504,6 +506,7 @@
|
||||
<div class="p-6">
|
||||
<input type="hidden" id="iaModalGuildId">
|
||||
<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>
|
||||
</div>
|
||||
<div class="p-4 border-t bg-gray-50 flex justify-end gap-3">
|
||||
@@ -520,100 +523,17 @@
|
||||
let cachedTemplates = {};
|
||||
let currentTemplateType = null;
|
||||
let localGuilds = [];
|
||||
let globalConfigStore = null; // Almacenamiento seguro global
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (!localStorage.getItem("token")) window.location.href = "index.html";
|
||||
showTab('templates');
|
||||
loadTemplates();
|
||||
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) {
|
||||
document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
|
||||
document.getElementById(`view-${tabId}`).classList.remove('hidden');
|
||||
@@ -630,85 +550,12 @@
|
||||
|
||||
if(tabId === 'others') { loadCompanies(); loadStatusesConfig(); }
|
||||
if(tabId === 'whatsapp') { checkWhatsappStatus(); }
|
||||
if(tabId === 'providers') { loadProviderCredentials(); loadIaRules(); }
|
||||
if(tabId === 'portal') { loadPortalConfig(); }
|
||||
if(tabId === 'app-operario') { loadAppConfig(); }
|
||||
if(tabId === 'providers') {
|
||||
loadProviderCredentials();
|
||||
loadIaRules();
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// LÓGICA PORTAL OPERARIO (PREVIEW COLORES)
|
||||
// ==========================================
|
||||
['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');
|
||||
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();
|
||||
|
||||
try {
|
||||
const resGuilds = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||
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;
|
||||
list.innerHTML = '';
|
||||
|
||||
localGuilds.forEach(g => {
|
||||
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');
|
||||
row.className = "p-4 hover:bg-purple-50/30 transition-colors grid grid-cols-12 gap-4 items-center group";
|
||||
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-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);
|
||||
});
|
||||
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) {
|
||||
@@ -760,11 +626,144 @@
|
||||
method: 'PUT', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||
body: JSON.stringify({ keywords: keywordsArray })
|
||||
});
|
||||
if (res.ok) { showToast("✅ Reglas IA guardadas"); closeIaModal(); loadIaRules(); }
|
||||
else { showToast("❌ Error al guardar", true); }
|
||||
if (res.ok) {
|
||||
showToast("✅ Reglas de IA guardadas correctamente.");
|
||||
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();
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// LÓGICA PLANTILLAS
|
||||
// ==========================================
|
||||
@@ -774,90 +773,198 @@
|
||||
const data = await res.json();
|
||||
if(data.ok) {
|
||||
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) {
|
||||
currentTemplateType = type;
|
||||
document.querySelectorAll('.tpl-btn').forEach(b => {
|
||||
b.classList.remove('bg-blue-50', 'ring-1', 'ring-blue-200');
|
||||
const span = 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 (span.classList.contains('bg-orange-600')) span.classList.replace('bg-orange-600', 'bg-orange-100'), span.classList.replace('text-white', 'text-orange-600');
|
||||
const s = b.querySelector('span');
|
||||
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(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');
|
||||
const activeSpan = 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');
|
||||
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');
|
||||
const span = btn.querySelector('span');
|
||||
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 (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('tplContent').value = cachedTemplates[type] || "";
|
||||
}
|
||||
|
||||
function insertVar(text) {
|
||||
const textarea = document.getElementById('tplContent');
|
||||
if (!textarea) return;
|
||||
const start = textarea.selectionStart, end = textarea.selectionEnd, val = textarea.value;
|
||||
textarea.value = val.substring(0, start) + text + val.substring(end);
|
||||
textarea.focus();
|
||||
textarea.selectionStart = textarea.selectionEnd = start + text.length;
|
||||
}
|
||||
|
||||
async function saveTemplate() {
|
||||
if(!currentTemplateType) { showToast("Selecciona plantilla", true); return; }
|
||||
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 }) });
|
||||
cachedTemplates[currentTemplateType] = content;
|
||||
showToast("Guardado");
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/templates`, {
|
||||
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() {
|
||||
const list = document.getElementById('listCompanies');
|
||||
list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>';
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||
const data = await res.json();
|
||||
const list = document.getElementById('listCompanies'); list.innerHTML = "";
|
||||
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>`; });
|
||||
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() {
|
||||
const name = document.getElementById('newCompanyInput').value;
|
||||
await fetch(`${API_URL}/companies`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ name }) });
|
||||
document.getElementById('newCompanyInput').value = ""; loadCompanies();
|
||||
const input = document.getElementById('newCompanyInput'), name = input.value.trim();
|
||||
if(!name) return;
|
||||
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() {
|
||||
const list = document.getElementById('listStatuses');
|
||||
list.innerHTML = '<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>';
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/statuses`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||
const data = await res.json();
|
||||
const list = document.getElementById('listStatuses'); list.innerHTML = "";
|
||||
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>`; });
|
||||
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 addStatus() {
|
||||
const input = document.getElementById('newStatusInput'), color = document.getElementById('newStatusColor').value, name = input.value.trim();
|
||||
if(!name) return;
|
||||
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 deleteStatus(id) {
|
||||
if(!confirm("¿Borrar estado?")) return;
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/statuses/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||
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();
|
||||
data.credentials.forEach(c => { const inp = document.getElementById(`user_${c.provider.toLowerCase()}`); if(inp) inp.value = c.username; });
|
||||
if(data.ok) {
|
||||
data.credentials.forEach(c => {
|
||||
const userInp = document.getElementById(`user_${c.provider.toLowerCase()}`);
|
||||
if(userInp) userInp.value = c.username;
|
||||
});
|
||||
}
|
||||
async function saveProviderCreds(event, provider) {
|
||||
event.preventDefault();
|
||||
const username = document.getElementById(`user_${provider}`).value, password = document.getElementById(`pass_${provider}`).value;
|
||||
if(!username || !password) return showToast("Faltan datos", true);
|
||||
await fetch(`${API_URL}/providers/credentials`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ provider, username, password }) });
|
||||
showToast(`✅ Acceso a ${provider} guardado`);
|
||||
} 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) {
|
||||
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`;
|
||||
m.innerText = msg;
|
||||
setTimeout(() => t.className += " opacity-0 translate-y-20", 3000);
|
||||
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; t.classList.remove('translate-y-20', 'opacity-0');
|
||||
setTimeout(() => t.classList.add('translate-y-20', 'opacity-0'), 3000);
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
Reference in New Issue
Block a user