Files
web/configuracion.html

385 lines
25 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Configuración - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>
.fade-in { animation: fadeIn 0.3s ease-in-out; }
.scroller::-webkit-scrollbar { width: 6px; }
.scroller::-webkit-scrollbar-thumb { background-color: #cbd5e1; border-radius: 4px; }
</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans h-screen overflow-hidden flex">
<div id="sidebar-container" class="h-full shrink-0"></div>
<div class="flex-1 flex flex-col h-full relative min-w-0">
<div id="header-container"></div>
<main class="flex-1 flex flex-col overflow-hidden relative">
<div class="bg-gray-50 p-6 pb-0 z-20 shrink-0">
<h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
<i data-lucide="settings" class="text-blue-600"></i> Configuración Avanzada
</h2>
<div class="flex border-b border-gray-200 overflow-x-auto no-scrollbar">
<button onclick="showTab('templates')" id="tab-templates" class="tab-btn px-6 py-3 text-sm font-bold text-blue-600 border-b-2 border-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
<i data-lucide="file-text" class="inline w-4 h-4 mr-1"></i> Plantillas
</button>
<button onclick="showTab('whatsapp')" id="tab-whatsapp" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
<i data-lucide="message-circle" class="inline w-4 h-4 mr-1"></i> WhatsApp
</button>
<button onclick="showTab('providers')" id="tab-providers" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
<i data-lucide="truck" class="inline w-4 h-4 mr-1"></i> Proveedores
</button>
<button onclick="showTab('portal')" id="tab-portal" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
<i data-lucide="globe" class="inline w-4 h-4 mr-1"></i> Portal Cliente
</button>
<button onclick="showTab('others')" id="tab-others" class="tab-btn px-6 py-3 text-sm font-medium text-gray-500 hover:text-blue-600 hover:bg-gray-100 transition whitespace-nowrap">
<i data-lucide="sliders" class="inline w-4 h-4 mr-1"></i> Otras Configuraciones
</button>
</div>
</div>
<div class="flex-1 overflow-hidden p-6 bg-gray-50">
<div id="view-templates" class="tab-content h-full fade-in flex flex-col md:flex-row gap-6">
<div class="w-full md:w-1/3 bg-white rounded-xl shadow border border-gray-100 overflow-hidden flex flex-col">
<div class="p-4 bg-gray-50 border-b border-gray-200 font-bold text-gray-700 text-sm uppercase tracking-wide">
Tipos de Mensaje
</div>
<div class="flex-1 overflow-y-auto p-2 space-y-1">
<button onclick="selectTemplate('welcome', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-3 group">
<span class="bg-blue-100 text-blue-600 p-1.5 rounded-md group-hover:bg-blue-200 transition"><i data-lucide="hand" class="w-4 h-4"></i></span>
Bienvenida / Alta
</button>
<button onclick="selectTemplate('no_contact', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-3 group">
<span class="bg-orange-100 text-orange-600 p-1.5 rounded-md group-hover:bg-orange-200 transition"><i data-lucide="phone-off" class="w-4 h-4"></i></span>
Cliente No Localizado
</button>
<button onclick="selectTemplate('appointment', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-3 group">
<span class="bg-green-100 text-green-600 p-1.5 rounded-md group-hover:bg-green-200 transition"><i data-lucide="calendar-check" class="w-4 h-4"></i></span>
Cita Creada
</button>
<button onclick="selectTemplate('update', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-3 group">
<span class="bg-purple-100 text-purple-600 p-1.5 rounded-md group-hover:bg-purple-200 transition"><i data-lucide="refresh-cw" class="w-4 h-4"></i></span>
Modificación de Servicio
</button>
<button onclick="selectTemplate('on_way', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-3 group">
<span class="bg-teal-100 text-teal-600 p-1.5 rounded-md group-hover:bg-teal-200 transition"><i data-lucide="truck" class="w-4 h-4"></i></span>
Técnico de Camino
</button>
<button onclick="selectTemplate('survey', this)" class="tpl-btn w-full text-left p-3 rounded-lg hover:bg-blue-50 text-sm font-medium text-gray-600 transition-colors flex items-center gap-3 group">
<span class="bg-yellow-100 text-yellow-600 p-1.5 rounded-md group-hover:bg-yellow-200 transition"><i data-lucide="star" class="w-4 h-4"></i></span>
Encuesta de Calidad
</button>
</div>
</div>
<div class="flex-1 bg-white rounded-xl shadow border border-gray-100 flex flex-col overflow-hidden">
<div class="p-4 border-b bg-gray-50 flex justify-between items-center shrink-0">
<div>
<span class="block font-bold text-gray-800" id="editorTitle">Selecciona una plantilla</span>
<span class="text-xs text-gray-500">Edita el mensaje que se enviará por WhatsApp/Email</span>
</div>
<button onclick="saveTemplate()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-bold shadow-lg transition-all transform active:scale-95 flex items-center gap-2">
<i data-lucide="save" class="w-4 h-4"></i> Guardar
</button>
</div>
<div class="p-3 border-b bg-gray-50/50 flex flex-wrap gap-2 items-center">
<span class="text-[10px] font-bold text-gray-400 uppercase tracking-wide mr-1">Insertar Variable:</span>
<button onclick="insertVar('{{NOMBRE}}')" class="px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono font-medium text-gray-600 hover:border-blue-400 hover:text-blue-600 transition shadow-sm" title="Nombre del cliente">{{NOMBRE}}</button>
<button onclick="insertVar('{{DIRECCION}}')" class="px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono font-medium text-gray-600 hover:border-blue-400 hover:text-blue-600 transition shadow-sm" title="Dirección del servicio">{{DIRECCION}}</button>
<button onclick="insertVar('{{FECHA}}')" class="px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono font-medium text-gray-600 hover:border-blue-400 hover:text-blue-600 transition shadow-sm" title="Fecha de la cita">{{FECHA}}</button>
<button onclick="insertVar('{{HORA}}')" class="px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono font-medium text-gray-600 hover:border-blue-400 hover:text-blue-600 transition shadow-sm" title="Hora de la cita">{{HORA}}</button>
<button onclick="insertVar('{{COMPANIA}}')" class="px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono font-medium text-gray-600 hover:border-blue-400 hover:text-blue-600 transition shadow-sm" title="Nombre de la aseguradora">{{COMPANIA}}</button>
<button onclick="insertVar('{{REFERENCIA}}')" class="px-2 py-1 bg-white border border-gray-200 rounded text-xs font-mono font-medium text-gray-600 hover:border-blue-400 hover:text-blue-600 transition shadow-sm" title="Nº Expediente">{{REFERENCIA}}</button>
</div>
<textarea id="tplContent" class="flex-1 p-6 outline-none resize-none text-sm leading-relaxed text-gray-700 font-sans" placeholder="Selecciona un tipo de mensaje a la izquierda para empezar a editar..."></textarea>
</div>
</div>
<div id="view-whatsapp" class="tab-content hidden h-full fade-in">
<div class="bg-white rounded-xl shadow p-10 text-center border border-gray-100">
<i data-lucide="message-circle" class="w-16 h-16 text-green-100 mx-auto mb-4 text-green-500"></i>
<h3 class="text-xl font-bold text-gray-700">Conexión WhatsApp</h3>
<p class="text-gray-500 mt-2">Próximamente</p>
</div>
</div>
<div id="view-providers" class="tab-content hidden h-full fade-in">
<div class="bg-white rounded-xl shadow p-10 text-center border border-gray-100">
<i data-lucide="truck" class="w-16 h-16 text-gray-200 mx-auto mb-4"></i>
<h3 class="text-xl font-bold text-gray-700">Proveedores</h3>
<p class="text-gray-500 mt-2">Próximamente</p>
</div>
</div>
<div id="view-portal" class="tab-content hidden h-full fade-in">
<div class="bg-white rounded-xl shadow p-10 text-center border border-gray-100">
<i data-lucide="globe" class="w-16 h-16 text-blue-200 mx-auto mb-4"></i>
<h3 class="text-xl font-bold text-gray-700">Portal del Cliente</h3>
<p class="text-gray-500 mt-2">Próximamente</p>
</div>
</div>
<div id="view-others" class="tab-content hidden h-full fade-in flex flex-col">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="bg-white rounded-xl shadow border border-gray-100 flex flex-col h-[500px]">
<div class="p-4 bg-gray-50 border-b border-gray-200 shrink-0">
<h3 class="font-bold text-gray-700 flex items-center gap-2">
<i data-lucide="shield" class="w-4 h-4 text-blue-600"></i> Compañías de Seguros
</h3>
</div>
<div class="p-4 border-b border-gray-100 bg-white">
<div class="flex gap-2">
<input type="text" id="newCompanyInput" placeholder="Nombre de la compañía..." class="flex-1 border rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-500">
<button onclick="addCompany()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold transition-colors">Añadir</button>
</div>
</div>
<div id="listCompanies" class="flex-1 overflow-y-auto scroller p-2 space-y-1">
<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>
</div>
</div>
<div class="bg-white rounded-xl shadow border border-gray-100 flex flex-col h-[500px]">
<div class="p-4 bg-gray-50 border-b border-gray-200 shrink-0">
<h3 class="font-bold text-gray-700 flex items-center gap-2">
<i data-lucide="activity" class="w-4 h-4 text-blue-600"></i> Estados del Servicio
</h3>
</div>
<div class="p-4 border-b border-gray-100 bg-white">
<div class="flex gap-2">
<input type="text" id="newStatusInput" placeholder="Nuevo estado..." class="flex-1 border rounded-lg px-3 py-2 text-sm outline-none focus:border-blue-500">
<select id="newStatusColor" class="border rounded-lg px-2 text-sm text-gray-600 outline-none focus:border-blue-500 bg-gray-50">
<option value="gray">Gris</option>
<option value="blue">Azul</option>
<option value="green">Verde</option>
<option value="red">Rojo</option>
<option value="yellow">Amarillo</option>
<option value="purple">Morado</option>
</select>
<button onclick="addStatus()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-xs font-bold transition-colors">Añadir</button>
</div>
</div>
<div id="listStatuses" class="flex-1 overflow-y-auto scroller p-2 space-y-1">
<p class="text-center text-xs text-gray-400 mt-10">Cargando...</p>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
<div id="toast" class="fixed bottom-5 right-5 bg-slate-800 text-white px-6 py-3 rounded-lg shadow-2xl transform translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center gap-3"><span id="toastMsg">Msg</span></div>
<script src="js/layout.js"></script>
<script>
// Variables globales
let cachedTemplates = {};
let currentTemplateType = null;
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) window.location.href = "index.html";
showTab('templates');
loadTemplates(); // Cargar plantillas al inicio
});
function showTab(tabId) {
document.querySelectorAll('.tab-content').forEach(el => el.classList.add('hidden'));
document.getElementById(`view-${tabId}`).classList.remove('hidden');
document.querySelectorAll('.tab-btn').forEach(el => {
el.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600', 'font-bold');
el.classList.add('text-gray-500', 'font-medium');
});
const btn = document.getElementById(`tab-${tabId}`);
btn.classList.add('text-blue-600', 'border-b-2', 'border-blue-600', 'font-bold');
btn.classList.remove('text-gray-500', 'font-medium');
if(tabId === 'others') {
loadCompanies();
loadStatusesConfig();
}
}
// ==========================================
// 📄 LÓGICA DE PLANTILLAS
// ==========================================
async function loadTemplates() {
try {
const res = await fetch(`${API_URL}/templates`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if(data.ok) {
data.templates.forEach(t => {
cachedTemplates[t.type] = t.content;
});
// Simular clic en la primera plantilla para cargar el editor
if (!currentTemplateType) {
const firstBtn = document.querySelector('.tpl-btn');
if(firstBtn) firstBtn.click();
}
}
} catch(e) { console.error("Error cargando plantillas"); }
}
function selectTemplate(type, btn) {
currentTemplateType = type;
// Estilos visuales
document.querySelectorAll('.tpl-btn').forEach(b => {
b.classList.remove('bg-blue-50', 'ring-1', 'ring-blue-200');
b.querySelector('span').classList.replace('bg-blue-600', 'bg-blue-100'); // Reset iconos si fuera necesario
b.querySelector('span').classList.replace('text-white', 'text-blue-600');
});
btn.classList.add('bg-blue-50', 'ring-1', 'ring-blue-200');
// Actualizar título y contenido del editor
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;
const end = textarea.selectionEnd;
const val = textarea.value;
// Insertar texto en la posición del cursor
textarea.value = val.substring(0, start) + text + val.substring(end);
// Reposicionar cursor después de la variable y enfocar
textarea.focus();
textarea.selectionStart = textarea.selectionEnd = start + text.length;
}
async function saveTemplate() {
if(!currentTemplateType) {
showToast("Selecciona un tipo de mensaje primero", true);
return;
}
const content = document.getElementById('tplContent').value;
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; // Actualizar cache local
showToast("✅ Plantilla guardada correctamente");
} else {
showToast("Error al guardar plantilla", true);
}
} catch(e) { showToast("Error de conexión", true); }
}
// ==========================================
// 🏢 LÓGICA DE 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();
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 input = document.getElementById('newCompanyInput');
const 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("Compañía añadida"); input.value = ""; loadCompanies(); }
} catch(e) { showToast("Error", true); }
}
async function deleteCompany(id) {
if(!confirm("¿Borrar compañía?")) return;
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();
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";
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>
<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>
`;
list.appendChild(div);
});
lucide.createIcons();
} catch(e) { list.innerHTML = '<p class="text-red-500 text-xs text-center">Error</p>'; }
}
async function addStatus() {
const input = document.getElementById('newStatusInput');
const color = document.getElementById('newStatusColor').value;
const 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("Estado 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")}` } });
const json = await res.json();
if(res.ok) { showToast("Estado eliminado"); loadStatusesConfig(); }
else { showToast(json.error || "No se pudo borrar", true); }
} catch(e) { showToast("Error conexión", true); }
}
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`;
m.innerText = msg; t.classList.remove('translate-y-20', 'opacity-0');
setTimeout(() => t.classList.add('translate-y-20', 'opacity-0'), 3000);
}
</script>
</body>
</html>