Actualizar configuracion.html
This commit is contained in:
@@ -497,7 +497,6 @@
|
|||||||
<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">
|
||||||
@@ -514,73 +513,102 @@
|
|||||||
let cachedTemplates = {};
|
let cachedTemplates = {};
|
||||||
let currentTemplateType = null;
|
let currentTemplateType = null;
|
||||||
let localGuilds = [];
|
let localGuilds = [];
|
||||||
let currentCompanyConfig = {}; // <--- ALMACENA TODA LA CONFIG GLOBAL
|
let globalConfig = null; // Para guardar la configuración de la base de datos
|
||||||
|
|
||||||
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();
|
||||||
loadGlobalCompanyConfig(); // <--- CARGA GLOBAL PARA EVITAR ERRORES
|
loadGlobalConfig(); // Cargar portal y app al iniciar
|
||||||
});
|
});
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// CARGA GLOBAL DE DATOS (ANTI-ERROR 500)
|
// Carga y Guardado Unificado (Evita Error 500)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
async function loadGlobalCompanyConfig() {
|
async function loadGlobalConfig() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
const res = await fetch(`${API_URL}/config/company`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
|
|
||||||
if (data.ok && data.config) {
|
if (data.ok && data.config) {
|
||||||
currentCompanyConfig = data.config;
|
globalConfig = data.config;
|
||||||
|
|
||||||
// Llenar datos Pestaña Portal
|
// Rellenar Portal
|
||||||
document.getElementById('confCompanyName').value = data.config.full_name || "";
|
document.getElementById('confCompanyName').value = globalConfig.full_name || "";
|
||||||
if (data.config.company_logo) {
|
if (globalConfig.company_logo) {
|
||||||
document.getElementById('confLogoBase64').value = data.config.company_logo;
|
document.getElementById('confLogoBase64').value = globalConfig.company_logo;
|
||||||
document.getElementById('logoPreview').innerHTML = `<img src="${data.config.company_logo}" class="w-full h-full object-contain">`;
|
document.getElementById('logoPreview').innerHTML = `<img src="${globalConfig.company_logo}" class="w-full h-full object-contain">`;
|
||||||
|
}
|
||||||
|
if (globalConfig.portal_settings) {
|
||||||
|
const s = globalConfig.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;
|
||||||
}
|
}
|
||||||
const ps = data.config.portal_settings || {};
|
|
||||||
if(ps.m_start) document.getElementById('mStart').value = ps.m_start;
|
|
||||||
if(ps.m_end) document.getElementById('mEnd').value = ps.m_end;
|
|
||||||
if(ps.a_start) document.getElementById('aStart').value = ps.a_start;
|
|
||||||
if(ps.a_end) document.getElementById('aEnd').value = ps.a_end;
|
|
||||||
|
|
||||||
// Llenar datos Pestaña App
|
// Rellenar App Operario (si existe en la BD)
|
||||||
const apps = ps.app_settings || {};
|
if (globalConfig.app_settings) {
|
||||||
document.getElementById('color-primary').value = apps.primary || "#2563EB";
|
const apps = globalConfig.app_settings;
|
||||||
document.getElementById('color-primary-hex').value = apps.primary || "#2563EB";
|
document.getElementById('color-primary').value = apps.primary || "#2563EB";
|
||||||
document.getElementById('color-secondary').value = apps.secondary || "#F59E0B";
|
document.getElementById('color-primary-hex').value = apps.primary || "#2563EB";
|
||||||
document.getElementById('color-secondary-hex').value = apps.secondary || "#F59E0B";
|
document.getElementById('color-secondary').value = apps.secondary || "#F59E0B";
|
||||||
document.getElementById('color-bg').value = apps.bg || "#F4F7F9";
|
document.getElementById('color-secondary-hex').value = apps.secondary || "#F59E0B";
|
||||||
document.getElementById('color-bg-hex').value = apps.bg || "#F4F7F9";
|
document.getElementById('color-bg').value = apps.bg || "#F4F7F9";
|
||||||
updateAppPreview();
|
document.getElementById('color-bg-hex').value = apps.bg || "#F4F7F9";
|
||||||
|
updateAppPreview();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch(e) { console.error("Error config global"); }
|
} catch (e) { console.error("Error cargando configuración global"); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// UNIFICADOR DE PAYLOAD (Evita enviar datos vacíos a la BD y crashear PostgreSQL)
|
async function saveConfigUnified(isPortal) {
|
||||||
function getCompanyPayload() {
|
let btnId = isPortal ? 'btnSavePortal' : 'btnSaveApp';
|
||||||
const portalSettings = currentCompanyConfig.portal_settings || {};
|
const btn = document.getElementById(btnId);
|
||||||
|
const original = btn.innerHTML;
|
||||||
|
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
|
||||||
|
lucide.createIcons();
|
||||||
|
|
||||||
portalSettings.m_start = document.getElementById('mStart').value || "09:00";
|
// Construir el objeto con TODO lo que espera el servidor
|
||||||
portalSettings.m_end = document.getElementById('mEnd').value || "14:00";
|
const payload = {
|
||||||
portalSettings.a_start = document.getElementById('aStart').value || "16:00";
|
company_name: document.getElementById('confCompanyName').value || globalConfig?.full_name || "Mi Empresa",
|
||||||
portalSettings.a_end = document.getElementById('aEnd').value || "19:00";
|
company_logo: document.getElementById('confLogoBase64').value || globalConfig?.company_logo || "",
|
||||||
|
portal_settings: {
|
||||||
portalSettings.app_settings = {
|
m_start: document.getElementById('mStart').value || "09:00",
|
||||||
primary: document.getElementById('color-primary').value || "#2563EB",
|
m_end: document.getElementById('mEnd').value || "14:00",
|
||||||
secondary: document.getElementById('color-secondary').value || "#F59E0B",
|
a_start: document.getElementById('aStart').value || "16:00",
|
||||||
bg: document.getElementById('color-bg').value || "#F4F7F9"
|
a_end: document.getElementById('aEnd').value || "19:00"
|
||||||
|
},
|
||||||
|
app_settings: {
|
||||||
|
primary: document.getElementById('color-primary').value || "#2563EB",
|
||||||
|
secondary: document.getElementById('color-secondary').value || "#F59E0B",
|
||||||
|
bg: document.getElementById('color-bg').value || "#F4F7F9"
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
try {
|
||||||
company_name: document.getElementById('confCompanyName').value || "",
|
const res = await fetch(`${API_URL}/config/company`, {
|
||||||
company_logo: document.getElementById('confLogoBase64').value || "",
|
method: 'POST',
|
||||||
portal_settings: portalSettings
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
||||||
};
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
|
||||||
|
if (data.ok) {
|
||||||
|
showToast(isPortal ? "✅ Portal Guardado" : "✅ Colores de la App Actualizados");
|
||||||
|
if(document.getElementById("headerUserName")) document.getElementById("headerUserName").innerText = payload.company_name;
|
||||||
|
localStorage.setItem('app_theme', JSON.stringify(payload.app_settings)); // Guardar en caché para la app móvil
|
||||||
|
} else {
|
||||||
|
showToast("❌ Error del servidor", true);
|
||||||
|
}
|
||||||
|
} catch (e) { showToast("Error de conexión", true); }
|
||||||
|
finally { btn.innerHTML = original; lucide.createIcons(); }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function savePortalConfig() { saveConfigUnified(true); }
|
||||||
|
function saveAppConfig() { saveConfigUnified(false); }
|
||||||
|
|
||||||
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');
|
||||||
@@ -601,21 +629,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// LÓGICA PORTAL OPERARIO (COLORES)
|
// LÓGICA PORTAL OPERARIO (PREVIEW COLORES)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
['primary', 'secondary', 'bg'].forEach(type => {
|
['primary', 'secondary', 'bg'].forEach(type => {
|
||||||
const picker = document.getElementById(`color-${type}`);
|
const picker = document.getElementById(`color-${type}`);
|
||||||
const text = document.getElementById(`color-${type}-hex`);
|
const text = document.getElementById(`color-${type}-hex`);
|
||||||
picker.addEventListener('input', (e) => {
|
picker.addEventListener('input', (e) => { text.value = e.target.value.toUpperCase(); updateAppPreview(); });
|
||||||
text.value = e.target.value.toUpperCase();
|
text.addEventListener('input', (e) => { if(/^#[0-9A-F]{6}$/i.test(e.target.value)) { picker.value = e.target.value; updateAppPreview(); } });
|
||||||
updateAppPreview();
|
|
||||||
});
|
|
||||||
text.addEventListener('input', (e) => {
|
|
||||||
if(/^#[0-9A-F]{6}$/i.test(e.target.value)) {
|
|
||||||
picker.value = e.target.value;
|
|
||||||
updateAppPreview();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
function updateAppPreview() {
|
function updateAppPreview() {
|
||||||
@@ -628,34 +648,6 @@
|
|||||||
document.getElementById('app-preview').style.backgroundColor = b;
|
document.getElementById('app-preview').style.backgroundColor = b;
|
||||||
}
|
}
|
||||||
|
|
||||||
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 payload = getCompanyPayload();
|
|
||||||
|
|
||||||
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)
|
|
||||||
});
|
|
||||||
const data = await res.json();
|
|
||||||
if (data.ok) {
|
|
||||||
showToast("✅ Colores de la App actualizados");
|
|
||||||
localStorage.setItem('app_theme', JSON.stringify(payload.portal_settings.app_settings));
|
|
||||||
} else {
|
|
||||||
showToast("❌ Error al guardar", true);
|
|
||||||
}
|
|
||||||
} catch (e) { showToast("Error de conexión", true); }
|
|
||||||
finally { btn.innerHTML = original; lucide.createIcons(); }
|
|
||||||
}
|
|
||||||
|
|
||||||
// ==========================================
|
|
||||||
// LÓGICA PORTAL CLIENTE
|
|
||||||
// ==========================================
|
|
||||||
function encodeLogo(input) {
|
function encodeLogo(input) {
|
||||||
const file = input.files[0];
|
const file = input.files[0];
|
||||||
if (!file || file.size > 1024 * 1024) { alert("Máximo 1MB"); return; }
|
if (!file || file.size > 1024 * 1024) { alert("Máximo 1MB"); return; }
|
||||||
@@ -667,30 +659,51 @@
|
|||||||
reader.readAsDataURL(file);
|
reader.readAsDataURL(file);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function savePortalConfig() {
|
// ==========================================
|
||||||
const btn = document.getElementById('btnSavePortal');
|
// LÓGICA WHATSAPP
|
||||||
const original = btn.innerHTML;
|
// ==========================================
|
||||||
btn.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> Guardando...';
|
async function loadWaSettings() {
|
||||||
lucide.createIcons();
|
|
||||||
|
|
||||||
const payload = getCompanyPayload();
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/config/company`, {
|
const res = await fetch(`${API_URL}/whatsapp/settings`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
method: 'POST',
|
|
||||||
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
|
|
||||||
body: JSON.stringify(payload)
|
|
||||||
});
|
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (data.ok) {
|
const s = data.settings || {};
|
||||||
showToast("✅ Configuración del Portal guardada");
|
document.getElementById('cfg_delay').checked = s.wa_delay_enabled !== false;
|
||||||
const nameEl = document.getElementById("headerUserName");
|
document.getElementById('cfg_evt_welcome').checked = s.wa_evt_welcome || false;
|
||||||
if (nameEl && payload.company_name) nameEl.innerText = payload.company_name;
|
document.getElementById('cfg_evt_assigned').checked = s.wa_evt_assigned || false;
|
||||||
} else {
|
document.getElementById('cfg_evt_date').checked = s.wa_evt_date || false;
|
||||||
showToast("❌ Error al guardar", true);
|
document.getElementById('cfg_evt_onway').checked = s.wa_evt_onway || false;
|
||||||
}
|
document.getElementById('cfg_evt_finished').checked = s.wa_evt_finished || false;
|
||||||
} catch (e) { showToast("Error de conexión", true); }
|
document.getElementById('cfg_evt_survey').checked = s.wa_evt_survey || false;
|
||||||
finally { btn.innerHTML = original; lucide.createIcons(); }
|
} 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"><i data-lucide="check-circle" class="w-12 h-12 mx-auto 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">Iniciando...</p>`;
|
||||||
|
lucide.createIcons();
|
||||||
|
} catch(e) { container.innerHTML = `<p class="text-red-500">Error servidor</p>`; }
|
||||||
}
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
@@ -736,7 +749,6 @@
|
|||||||
});
|
});
|
||||||
lucide.createIcons();
|
lucide.createIcons();
|
||||||
} catch (e) {
|
} 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>';
|
list.innerHTML = '<p class="text-center text-sm text-red-500 py-8">Error al cargar las reglas de IA.</p>';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -762,69 +774,39 @@
|
|||||||
body: JSON.stringify({ keywords: keywordsArray })
|
body: JSON.stringify({ keywords: keywordsArray })
|
||||||
});
|
});
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
showToast("✅ Reglas de IA guardadas correctamente.");
|
showToast("✅ Reglas de IA guardadas.");
|
||||||
closeIaModal();
|
closeIaModal();
|
||||||
loadIaRules();
|
loadIaRules();
|
||||||
} else { showToast("❌ Error al guardar las reglas.", true); }
|
} else { showToast("❌ Error al guardar reglas.", true); }
|
||||||
} catch (e) { showToast("❌ Error de conexión.", true); }
|
} catch (e) { showToast("❌ Error de conexión.", true); }
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadWaSettings() {
|
// ==========================================
|
||||||
try {
|
// LÓGICA PLANTILLAS
|
||||||
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"><i data-lucide="check-circle" class="w-12 h-12 mx-auto 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">Iniciando...</p>`;
|
|
||||||
lucide.createIcons();
|
|
||||||
} catch(e) { container.innerHTML = `<p class="text-red-500">Error servidor</p>`; }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function loadTemplates() {
|
async function loadTemplates() {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${API_URL}/templates`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
const res = await fetch(`${API_URL}/templates`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
const data = await res.json();
|
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(data.ok) {
|
||||||
|
data.templates.forEach(t => { cachedTemplates[t.type] = t.content; });
|
||||||
|
if (!currentTemplateType) document.querySelector('.tpl-btn').click();
|
||||||
|
}
|
||||||
} catch(e) {}
|
} catch(e) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectTemplate(type, btn) {
|
function selectTemplate(type, btn) {
|
||||||
currentTemplateType = type;
|
currentTemplateType = type;
|
||||||
document.querySelectorAll('.tpl-btn').forEach(b => b.classList.remove('bg-blue-50', 'ring-1', 'ring-blue-200'));
|
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');
|
||||||
|
});
|
||||||
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');
|
||||||
|
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');
|
||||||
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] || "";
|
||||||
}
|
}
|
||||||
@@ -843,6 +825,9 @@
|
|||||||
showToast("Guardado");
|
showToast("Guardado");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ==========================================
|
||||||
|
// LÓGICA OTROS Y PROVEEDORES
|
||||||
|
// ==========================================
|
||||||
async function loadCompanies() {
|
async function loadCompanies() {
|
||||||
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
const res = await fetch(`${API_URL}/companies`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
@@ -850,13 +835,11 @@
|
|||||||
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>`; });
|
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>`; });
|
||||||
lucide.createIcons();
|
lucide.createIcons();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addCompany() {
|
async function addCompany() {
|
||||||
const name = document.getElementById('newCompanyInput').value;
|
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 }) });
|
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();
|
document.getElementById('newCompanyInput').value = ""; 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 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() {
|
||||||
@@ -866,23 +849,24 @@
|
|||||||
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>`; });
|
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>`; });
|
||||||
lucide.createIcons();
|
lucide.createIcons();
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addStatus() {
|
async function addStatus() {
|
||||||
const name = document.getElementById('newStatusInput').value;
|
const name = document.getElementById('newStatusInput').value, color = document.getElementById('newStatusColor').value;
|
||||||
const 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 }) });
|
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();
|
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 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 loadProviderCredentials() {
|
||||||
const res = await fetch(`${API_URL}/providers/credentials`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
const res = await fetch(`${API_URL}/providers/credentials`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
data.credentials.forEach(c => {
|
data.credentials.forEach(c => { const inp = document.getElementById(`user_${c.provider.toLowerCase()}`); if(inp) inp.value = c.username; });
|
||||||
const inp = document.getElementById(`user_${c.provider.toLowerCase()}`);
|
}
|
||||||
if(inp) inp.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`);
|
||||||
}
|
}
|
||||||
|
|
||||||
function showToast(msg, isError = false) {
|
function showToast(msg, isError = false) {
|
||||||
@@ -891,8 +875,6 @@
|
|||||||
m.innerText = msg;
|
m.innerText = msg;
|
||||||
setTimeout(() => t.className += " opacity-0 translate-y-20", 3000);
|
setTimeout(() => t.className += " opacity-0 translate-y-20", 3000);
|
||||||
}
|
}
|
||||||
|
|
||||||
function logout() { localStorage.clear(); window.location.href = "index.html"; }
|
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
Reference in New Issue
Block a user