Files
web/usuarios.html
2026-02-15 17:17:55 +00:00

490 lines
29 KiB
HTML

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Gestión de Usuarios - IntegraRepara</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://unpkg.com/lucide@latest"></script>
<style>.fade-in { animation: fadeIn 0.5s ease-in-out; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .no-scrollbar::-webkit-scrollbar { display: none; }</style>
</head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased text-left">
<div class="flex h-screen overflow-hidden text-left">
<div id="sidebar-container" class="h-full shrink-0"></div>
<div class="flex-1 flex flex-col overflow-hidden relative">
<div id="header-container"></div>
<main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-50 p-8 fade-in">
<h2 class="text-2xl font-bold text-gray-800 mb-8 text-left">Gestión de Equipo y Zonas</h2>
<div class="flex flex-col gap-8 max-w-5xl mx-auto text-left">
<div class="w-full bg-white p-6 rounded-xl shadow-sm border border-gray-100">
<div class="flex items-center gap-3 mb-4 text-blue-600 text-left">
<i data-lucide="hammer" class="w-6 h-6"></i>
<h3 class="text-lg font-bold text-gray-800">1. Gremios / Especialidades</h3>
</div>
<div class="flex flex-col md:flex-row gap-6 text-left">
<form onsubmit="addGuild(event)" class="flex gap-2 h-10 w-full md:w-1/2 text-left">
<input type="text" id="newGuildName" placeholder="NUEVO GREMIO (EJ. LIMPIEZA)" required class="flex-1 px-3 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 outline-none text-sm uppercase">
<button type="submit" class="bg-slate-800 text-white px-4 rounded-lg hover:bg-slate-700 font-bold"><i data-lucide="plus" class="w-5 h-5"></i></button>
</form>
<div class="w-full md:w-1/2 border rounded-lg bg-gray-50 p-2 max-h-40 overflow-y-auto space-y-2 no-scrollbar" id="guildsList"></div>
</div>
</div>
<div class="w-full bg-white p-6 rounded-xl shadow-sm border border-gray-100 relative text-left">
<button onclick="resetUserForm()" id="btnCancelEdit" class="hidden absolute top-6 right-6 text-sm text-red-500 hover:underline font-bold">Cancelar Edición</button>
<div class="flex items-center gap-3 mb-6 text-green-600 text-left">
<i data-lucide="user-plus" class="w-6 h-6"></i>
<h3 class="text-lg font-bold text-gray-800" id="formTitle">2. Ficha de Usuario y Cobertura</h3>
</div>
<form onsubmit="handleUserSubmit(event)" class="space-y-6 text-left">
<input type="hidden" id="editUserId">
<div class="grid grid-cols-1 md:grid-cols-2 gap-6 text-left">
<div class="space-y-4">
<div>
<label class="block text-xs font-black text-gray-400 uppercase mb-1">Nombre Completo</label>
<input type="text" id="uName" required class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none font-bold">
</div>
<div>
<label class="block text-xs font-black text-gray-400 uppercase mb-1">Correo Electrónico</label>
<input type="email" id="uEmail" required class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none">
</div>
</div>
<div class="space-y-4">
<div>
<label class="block text-xs font-black text-gray-400 uppercase mb-1">Teléfono</label>
<input type="tel" id="uPhone" required placeholder="+34 600..." class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none font-bold text-green-700">
</div>
<div class="flex gap-4 text-left">
<div class="w-1/2">
<label class="block text-xs font-black text-gray-400 uppercase mb-1">Rol</label>
<select id="uRole" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none bg-white font-bold">
<option value="operario">Operario</option>
<option value="facturacion">Facturación</option>
<option value="admin">Administrador</option>
</select>
</div>
<div class="w-1/2">
<label class="block text-xs font-black text-gray-400 uppercase mb-1">Contraseña</label>
<input type="password" id="uPass" class="w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-green-500 outline-none" placeholder="••••••••">
</div>
</div>
</div>
</div>
<div class="pt-2 text-left">
<label class="block text-xs font-black text-gray-400 uppercase mb-2">Gremios Asignados</label>
<div class="p-4 border rounded-lg bg-gray-50 grid grid-cols-2 md:grid-cols-4 gap-3 text-left" id="guildsCheckboxArea"></div>
</div>
<div class="pt-2 text-left">
<label class="block text-xs font-black text-blue-600 uppercase mb-2 tracking-widest text-left">Cobertura Geográfica (Toda España)</label>
<div class="bg-blue-50/50 border-2 border-blue-100 rounded-2xl p-5 space-y-4 text-left">
<div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-left">
<div>
<label class="block text-[10px] font-bold text-blue-500 mb-1 uppercase">1. Provincia</label>
<select id="selProvince" onchange="fetchMunicipios(this.value)" class="w-full text-sm p-2.5 border rounded-lg outline-none focus:border-blue-500 font-bold bg-white">
<option value="">-- Seleccionar --</option>
</select>
</div>
<div class="relative text-left">
<label class="block text-[10px] font-bold text-blue-500 mb-1 uppercase text-left">2. Municipio</label>
<select id="selMunicipio" onchange="autoFillCP(this.value)" class="w-full text-sm p-2.5 border rounded-lg outline-none focus:border-blue-500 font-bold bg-white disabled:opacity-50" disabled>
<option value="">-- Elige Municipio --</option>
</select>
<div id="loaderMun" class="hidden absolute right-10 top-9"><i data-lucide="loader-2" class="w-4 h-4 animate-spin text-blue-500"></i></div>
</div>
<div class="text-left">
<label class="block text-[10px] font-bold text-blue-500 mb-1 uppercase text-left">3. Código(s) Postal(es)</label>
<div class="flex gap-1 text-left">
<input type="text" id="cpInput" placeholder="Ej: 11201-11207" class="flex-1 text-sm p-2.5 border rounded-lg font-black outline-none focus:border-blue-500 text-blue-700">
<button type="button" onclick="addZoneToUser()" class="bg-blue-600 text-white px-4 rounded-lg font-black hover:bg-blue-700 transition-all shadow-md active:scale-95">
<i data-lucide="plus" class="w-5 h-5"></i>
</button>
</div>
</div>
</div>
<div id="userZonesArea" class="flex flex-wrap gap-2 min-h-[50px] p-3 bg-white rounded-xl border border-blue-100 shadow-inner text-left"></div>
</div>
</div>
<div class="pt-4 border-t border-gray-100 text-left">
<button type="submit" id="btnSubmitUser" class="w-full bg-green-600 hover:bg-green-700 text-white font-black py-4 rounded-xl transition-all shadow-lg shadow-green-500/30 uppercase tracking-widest text-sm text-left justify-center flex items-center">
Guardar Usuario y Zonas
</button>
</div>
</form>
</div>
<div class="w-full bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden text-left">
<div class="p-6 border-b border-gray-100 bg-gray-50 text-left">
<h3 class="font-bold text-gray-800">Listado de Equipo</h3>
</div>
<div class="overflow-x-auto no-scrollbar text-left">
<table class="w-full text-left border-collapse">
<thead>
<tr class="bg-white text-gray-400 text-[10px] font-black uppercase tracking-[0.2em] border-b text-left">
<th class="p-4">Personal</th>
<th class="p-4">Contacto</th>
<th class="p-4">Rol / Gremios</th>
<th class="p-4">Zonas Cobertura</th>
<th class="p-4 text-right">Acciones</th>
</tr>
</thead>
<tbody id="usersListBody" class="text-sm divide-y divide-gray-100 text-left"></tbody>
</table>
</div>
</div>
</div>
</main>
</div>
</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">Mensaje</span></div>
<script src="js/layout.js"></script>
<script>
let availableGuilds = [];
let currentUsers = [];
let tempUserZones = [];
const provinciasES = ["Álava","Albacete","Alicante","Almería","Asturias","Ávila","Badajoz","Baleares","Barcelona","Burgos","Cáceres","Cádiz","Cantabria","Castellón","Ciudad Real","Córdoba","A Coruña","Cuenca","Gipuzkoa","Girona","Granada","Guadalajara","Huelva","Huesca","Jaén","León","Lleida","Lugo","Madrid","Málaga","Murcia","Navarra","Ourense","Palencia","Las Palmas","Pontevedra","La Rioja","Salamanca","Segovia","Sevilla","Soria","Tarragona","Santa Cruz de Tenerife","Teruel","Toledo","Valencia","Valladolid","Bizkaia","Zamora","Zaragoza","Ceuta","Melilla"];
document.addEventListener("DOMContentLoaded", () => {
if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; }
fetchGuilds();
fetchUsers();
setupProvinceSelect();
});
function setupProvinceSelect() {
const sel = document.getElementById('selProvince');
if(!sel) return;
sel.innerHTML = '<option value="">-- Seleccionar --</option>';
provinciasES.sort().forEach(p => {
const opt = document.createElement('option');
opt.value = p.toUpperCase();
opt.innerText = p.toUpperCase();
sel.appendChild(opt);
});
}
// 1. Cargamos municipios AGRUPADOS por nombre
async function fetchMunicipios(provName) {
const selMun = document.getElementById('selMunicipio');
const loader = document.getElementById('loaderMun');
selMun.innerHTML = '<option value="">-- Cargando... --</option>';
selMun.disabled = true;
if(!provName) return;
if (loader) loader.classList.remove('hidden');
try {
const res = await fetch(`${API_URL}/api/geo/municipios/${provName}`, {
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
});
const data = await res.json();
if (data.ok && data.municipios.length > 0) {
// Agrupamos códigos por municipio
const grouped = data.municipios.reduce((acc, m) => {
if(!acc[m.municipio]) acc[m.municipio] = [];
acc[m.municipio].push(m.codigo_postal);
return acc;
}, {});
selMun.innerHTML = '<option value="">-- Selecciona Pueblo --</option>';
Object.keys(grouped).sort().forEach(mun => {
const opt = document.createElement('option');
opt.value = mun;
// Guardamos el array de códigos en un dataset
opt.dataset.cps = JSON.stringify(grouped[mun]);
opt.innerText = `${mun.toUpperCase()} (${grouped[mun].length} CPs)`;
selMun.appendChild(opt);
});
selMun.innerHTML += '<option value="OTRO">-- NO ESTÁ EN LA LISTA (MANUAL) --</option>';
selMun.disabled = false;
}
} catch (e) { console.error(e); }
finally { if (loader) loader.classList.add('hidden'); }
}
// 2. Añadimos todos los códigos del municipio de una vez
function addZoneToUser() {
const prov = document.getElementById('selProvince').value;
const selMun = document.getElementById('selMunicipio');
const munName = selMun.value;
if (!prov || !munName) { showToast("Selecciona Provincia y Municipio", true); return; }
if (munName === "OTRO") {
const manualCP = document.getElementById('cpInput').value.trim();
if(!manualCP) { showToast("Escribe el CP manual", true); return; }
tempUserZones.push({ province: prov, city: "MANUAL", cps: manualCP });
} else {
// Extraemos la lista de CPs del pueblo seleccionado
const cpList = JSON.parse(selMun.options[selMun.selectedIndex].dataset.cps);
cpList.forEach(cp => {
// Evitamos duplicados antes de añadir
if (!tempUserZones.some(z => z.city === munName && z.cps === cp)) {
tempUserZones.push({ province: prov, city: munName, cps: cp });
}
});
showToast(`✅ Añadidos ${cpList.length} códigos de ${munName}`);
}
renderTempZones();
document.getElementById('cpInput').value = "";
}
function autoFillCP(munName) {
const sel = document.getElementById('selMunicipio');
const selectedOpt = sel.options[sel.selectedIndex];
if (munName === "OTRO") {
const customMun = prompt("Nombre del Municipio:");
if (customMun) {
const newOpt = document.createElement('option');
newOpt.value = customMun.toUpperCase();
newOpt.innerText = customMun.toUpperCase();
newOpt.selected = true;
sel.appendChild(newOpt);
document.getElementById('cpInput').focus();
}
return;
}
if(selectedOpt && selectedOpt.dataset.cp) {
document.getElementById('cpInput').value = selectedOpt.dataset.cp;
}
}
function addZoneToUser() {
const prov = document.getElementById('selProvince').value;
const mun = document.getElementById('selMunicipio').value;
const cp = document.getElementById('cpInput').value.trim();
if (!prov || !mun || !cp || mun === "OTRO") { showToast("Completa los datos de zona", true); return; }
if (tempUserZones.some(z => z.city === mun && z.cps === cp)) {
showToast("Esta zona ya está añadida", true); return;
}
tempUserZones.push({ province: prov, city: mun, cps: cp });
renderTempZones();
document.getElementById('cpInput').value = "";
}
function removeTempZone(idx) {
tempUserZones.splice(idx, 1);
renderTempZones();
}
function renderTempZones() {
const area = document.getElementById('userZonesArea');
area.innerHTML = tempUserZones.length === 0 ? '<p class="text-[10px] text-gray-300 italic p-1">Sin zonas añadidas...</p>' : "";
tempUserZones.forEach((z, i) => {
area.innerHTML += `
<span class="bg-blue-100 text-blue-700 px-3 py-1.5 rounded-lg text-[10px] font-black border border-blue-200 flex items-center gap-2">
${z.city} (${z.cps})
<button type="button" onclick="removeTempZone(${i})" class="text-blue-400 hover:text-red-500"><i data-lucide="x" class="w-3 h-3"></i></button>
</span>`;
});
lucide.createIcons();
}
async function fetchGuilds() {
try {
const res = await fetch(`${API_URL}/guilds`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
availableGuilds = data.guilds;
renderGuildsList();
renderGuildsCheckboxes();
}
} catch (e) {}
}
async function addGuild(e) {
e.preventDefault();
const name = document.getElementById('newGuildName').value.toUpperCase();
try {
await fetch(`${API_URL}/guilds`, { method: 'POST', headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` }, body: JSON.stringify({ name }) });
document.getElementById('newGuildName').value = ""; fetchGuilds(); showToast("Gremio añadido");
} catch (e) { showToast("Error", true); }
}
async function deleteGuild(id) {
if(!confirm("¿Borrar gremio?")) return;
try {
await fetch(`${API_URL}/guilds/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
fetchGuilds(); showToast("Gremio eliminado");
} catch(e) { showToast("Error", true); }
}
async function fetchUsers() {
try {
const res = await fetch(`${API_URL}/admin/users`, { headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
const data = await res.json();
if (data.ok) {
currentUsers = data.users;
renderUsersTable();
}
} catch (e) {}
}
async function handleUserSubmit(e) {
e.preventDefault();
const userId = document.getElementById('editUserId').value;
const isEdit = !!userId;
const btn = document.getElementById('btnSubmitUser');
btn.disabled = true; btn.innerText = "PROCESANDO...";
const selectedGuilds = Array.from(document.querySelectorAll('.guild-checkbox:checked')).map(cb => cb.value);
const data = {
fullName: document.getElementById('uName').value,
email: document.getElementById('uEmail').value,
phone: document.getElementById('uPhone').value,
password: document.getElementById('uPass').value,
role: document.getElementById('uRole').value,
guilds: selectedGuilds,
zones: tempUserZones
};
const url = isEdit ? `${API_URL}/admin/users/${userId}` : `${API_URL}/admin/users`;
try {
const res = await fetch(url, {
method: isEdit ? 'PUT' : 'POST',
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${localStorage.getItem("token")}` },
body: JSON.stringify(data)
});
const json = await res.json();
if (json.ok) {
showToast(isEdit ? "Datos actualizados" : "Usuario creado");
resetUserForm();
fetchUsers();
} else { showToast("❌ " + (json.error || "Error"), true); }
} catch (e) { showToast("Error conexión", true); }
finally { btn.disabled = false; btn.innerText = isEdit ? "Actualizar Datos" : "Guardar Usuario y Zonas"; }
}
function editUser(id) {
const user = currentUsers.find(u => u.id === id);
if(!user) return;
document.getElementById('editUserId').value = user.id;
document.getElementById('uName').value = user.full_name;
document.getElementById('uEmail').value = user.email;
document.getElementById('uPhone').value = user.phone;
document.getElementById('uRole').value = user.role;
document.getElementById('uPass').value = "";
tempUserZones = user.zones || [];
renderTempZones();
const userGuilds = user.guilds || [];
document.querySelectorAll('.guild-checkbox').forEach(cb => {
cb.checked = userGuilds.includes(parseInt(cb.value));
});
document.getElementById('formTitle').innerText = "2. Editando Usuario";
document.getElementById('btnSubmitUser').classList.replace('bg-green-600', 'bg-blue-600');
document.getElementById('btnCancelEdit').classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
async function deleteUser(id) {
if(!confirm("¿Seguro que quieres borrar a este usuario?")) return;
try {
await fetch(`${API_URL}/admin/users/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
fetchUsers(); showToast("Usuario borrado");
} catch(e) { showToast("Error", true); }
}
function resetUserForm() {
document.getElementById('editUserId').value = "";
document.getElementById('uName').value = "";
document.getElementById('uEmail').value = "";
document.getElementById('uPhone').value = "";
document.getElementById('uPass').value = "";
tempUserZones = [];
renderTempZones();
document.getElementById('formTitle').innerText = "2. Nuevo Usuario";
document.getElementById('btnSubmitUser').classList.replace('bg-blue-600', 'bg-green-600');
document.getElementById('btnCancelEdit').classList.add('hidden');
document.querySelectorAll('.guild-checkbox').forEach(cb => cb.checked = false);
}
function renderGuildsList() {
const list = document.getElementById('guildsList');
list.innerHTML = "";
availableGuilds.forEach(g => {
list.innerHTML += `<div class="flex justify-between items-center bg-white p-2 rounded border shadow-sm"><span class="text-xs font-black uppercase text-slate-700">${g.name}</span><button type="button" onclick="deleteGuild(${g.id})" class="text-gray-400 hover:text-red-500 transition-colors text-left"><i data-lucide="trash-2" class="w-3.5 h-3.5 text-left"></i></button></div>`;
});
lucide.createIcons();
}
function renderGuildsCheckboxes() {
const area = document.getElementById('guildsCheckboxArea');
area.innerHTML = availableGuilds.length === 0 ? '<p class="text-xs text-gray-300 italic">No hay gremios registrados...</p>' : "";
availableGuilds.forEach(g => {
area.innerHTML += `<label class="flex items-center space-x-2 cursor-pointer p-2 hover:bg-white rounded border border-transparent hover:border-green-200 transition-all text-left"><input type="checkbox" value="${g.id}" class="guild-checkbox h-4 w-4 text-green-600 border-gray-300 rounded text-left"><span class="text-[10px] font-black uppercase text-slate-500 text-left">${g.name}</span></label>`;
});
}
function renderUsersTable() {
const tbody = document.getElementById('usersListBody');
tbody.innerHTML = currentUsers.length === 0 ? `<tr><td colspan="5" class="p-8 text-center text-gray-300 font-bold uppercase tracking-widest text-left">Cargando equipo...</td></tr>` : "";
currentUsers.forEach(u => {
const uGuildNames = (u.guilds || []).map(gid => availableGuilds.find(ag => ag.id === gid)?.name).filter(Boolean).join(", ");
// --- LÓGICA DE AGRUPACIÓN POR MUNICIPIO ---
const groupedZones = (u.zones || []).reduce((acc, current) => {
if (!acc[current.city]) {
acc[current.city] = [];
}
// Evitamos duplicados de CP en la misma ciudad
if (!acc[current.city].includes(current.cps)) {
acc[current.city].push(current.cps);
}
return acc;
}, {});
// Convertimos el objeto agrupado en HTML elegante
const uZonesHtml = Object.keys(groupedZones).map(city => {
const cps = groupedZones[city].join(", ");
return `<div class="mb-1 last:mb-0">
<span class="font-black text-blue-600 text-[10px] uppercase">📍 ${city}</span>
<span class="text-gray-500 text-[9px] font-medium">(${cps})</span>
</div>`;
}).join("") || '<span class="text-[9px] text-gray-300 italic text-left">Sin zona</span>';
tbody.innerHTML += `
<tr class="bg-white hover:bg-gray-50 transition border-b text-left">
<td class="p-4"><div class="flex flex-col text-left"><span class="font-black text-slate-800 uppercase text-left">${u.full_name}</span><span class="text-[9px] text-gray-400 font-bold tracking-tighter text-left">${u.email}</span></div></td>
<td class="p-4 font-black text-green-600 text-left">${u.phone}</td>
<td class="p-4 text-left"><span class="bg-slate-100 text-slate-600 px-2 py-0.5 rounded text-[10px] font-black uppercase text-left">${u.role}</span><p class="text-[9px] text-gray-400 mt-1 uppercase font-bold text-left">${uGuildNames || '-'}</p></td>
<td class="p-4 text-left">
<div class="max-h-24 overflow-y-auto no-scrollbar">
${uZonesHtml}
</div>
</td>
<td class="p-4 text-right space-x-3 text-left">
<button onclick="editUser(${u.id})" class="text-blue-500 hover:text-blue-700 font-black text-xs uppercase tracking-widest text-left">Editar</button>
<button onclick="deleteUser(${u.id})" class="text-red-400 hover:text-red-700 font-black text-xs uppercase tracking-widest text-left">Baja</button>
</td>
</tr>`;
});
}
function showToast(msg, err=false){
const t=document.getElementById('toast'), m=document.getElementById('toastMsg');
t.className=`fixed bottom-5 right-5 px-6 py-3 rounded-xl shadow-2xl transition-all duration-300 z-50 flex items-center gap-3 font-bold ${err?'bg-red-600':'bg-slate-900'} text-white`;
m.innerText=msg; t.classList.remove('translate-y-20','opacity-0');
setTimeout(()=>t.classList.add('translate-y-20','opacity-0'),3000);
}
</script>
</body>
</html>