Actualizar usuarios.html

This commit is contained in:
2026-02-15 16:03:34 +00:00
parent 57a0ee8756
commit 39f23cbc62

View File

@@ -6,107 +6,136 @@
<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; } }</style>
<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">
<body class="bg-gray-50 text-gray-800 font-sans antialiased text-left">
<div class="flex h-screen overflow-hidden">
<div id="sidebar-container" class="h-full"></div>
<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">Gestión de Equipo</h2>
<h2 class="text-2xl font-bold text-gray-800 mb-8">Gestión de Equipo y Zonas</h2>
<div class="flex flex-col gap-8 max-w-5xl mx-auto">
<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">
<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">
<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">
<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" id="guildsList"><p class="text-xs text-center text-gray-400 mt-2">Cargando...</p></div>
<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">
<button onclick="resetUserForm()" id="btnCancelEdit" class="hidden absolute top-6 right-6 text-sm text-red-500 hover:underline">Cancelar Edición</button>
<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">
<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. Nuevo Usuario</h3>
<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">
<input type="hidden" id="editUserId"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<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">
<div class="space-y-4">
<div>
<label class="block text-xs font-bold text-gray-600 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">
<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-bold text-gray-600 mb-1">Correo Electrónico</label>
<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-bold text-gray-600 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">
<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">
<div class="w-1/2">
<label class="block text-xs font-bold text-gray-600 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">
<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-bold text-gray-600 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="Opcional al editar">
<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">
<label class="block text-xs font-bold text-gray-600 mb-2">Asignar Gremios</label>
<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" id="guildsCheckboxArea"></div>
</div>
<div class="pt-4 border-t border-gray-100">
<button type="submit" id="btnSubmitUser" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 rounded-lg transition-all shadow-lg shadow-green-500/30">
Guardar Usuario
<div class="pt-2 text-left">
<label class="block text-xs font-black text-blue-600 uppercase mb-2 tracking-widest">Cobertura Geográfica (Zonas de Trabajo)</label>
<div class="bg-blue-50/50 border-2 border-blue-100 rounded-2xl p-5 space-y-4">
<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
<div>
<label class="block text-[10px] font-bold text-blue-500 mb-1">Provincia</label>
<select id="selProvince" class="w-full text-sm p-2 border rounded-lg outline-none focus:border-blue-500 font-bold">
<option value="">Seleccionar...</option>
<option value="CADIZ">CADIZ</option>
<option value="MALAGA">MALAGA</option>
<option value="SEVILLA">SEVILLA</option>
</select>
</div>
<div>
<label class="block text-[10px] font-bold text-blue-500 mb-1">Municipio (Ej. Algeciras)</label>
<input type="text" id="cityName" placeholder="ALGECIRAS" class="w-full text-sm p-2 border rounded-lg uppercase font-bold outline-none">
</div>
<div>
<label class="block text-[10px] font-bold text-blue-500 mb-1">Códigos Postales (Rango o Indiv.)</label>
<div class="flex gap-1">
<input type="text" id="cpInput" placeholder="11201-11207" class="flex-1 text-sm p-2 border rounded-lg font-black outline-none">
<button type="button" onclick="addZoneToUser()" class="bg-blue-600 text-white px-3 rounded-lg font-bold"><i data-lucide="plus" class="w-4 h-4"></i></button>
</div>
</div>
</div>
<div id="userZonesArea" class="flex flex-wrap gap-2 min-h-[40px] p-2 bg-white rounded-xl border border-blue-100">
</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">
Guardar Usuario y Zonas
</button>
</div>
</form>
</div>
<div class="w-full bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
<div class="p-6 border-b border-gray-100 bg-gray-50">
<h3 class="font-bold text-gray-800">Listado de Personal</h3>
<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 flex justify-between items-center">
<h3 class="font-bold text-gray-800">Listado de Equipo</h3>
</div>
<div class="overflow-x-auto">
<div class="overflow-x-auto no-scrollbar">
<table class="w-full text-left border-collapse">
<thead>
<tr class="bg-white text-gray-500 text-xs uppercase tracking-wider border-b">
<th class="p-4">Nombre</th>
<tr class="bg-white text-gray-400 text-[10px] font-black uppercase tracking-[0.2em] border-b">
<th class="p-4">Personal</th>
<th class="p-4">Contacto</th>
<th class="p-4">Rol</th>
<th class="p-4">Gremios</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">
<tr><td colspan="5" class="p-4 text-center text-gray-400">Cargando...</td></tr>
</tbody>
<tbody id="usersListBody" class="text-sm divide-y divide-gray-100"></tbody>
</table>
</div>
</div>
@@ -122,14 +151,46 @@
<script>
let availableGuilds = [];
let currentUsers = [];
let tempUserZones = []; // [{city: 'ALGECIRAS', cps: '11201-11207'}]
document.addEventListener("DOMContentLoaded", () => {
const token = localStorage.getItem("token");
if (!token) { window.location.href = "index.html"; return; }
if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; }
fetchGuilds();
fetchUsers();
});
// --- ZONAS DE TRABAJO ---
function addZoneToUser() {
const city = document.getElementById('cityName').value.trim().toUpperCase();
const cps = document.getElementById('cpInput').value.trim();
const province = document.getElementById('selProvince').value;
if(!city || !cps || !province) { showToast("Faltan datos de zona", true); return; }
tempUserZones.push({ city, cps, province });
document.getElementById('cityName').value = "";
document.getElementById('cpInput').value = "";
renderTempZones();
}
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 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();
}
// --- GREMIOS ---
async function fetchGuilds() {
try {
@@ -140,21 +201,17 @@
renderGuildsList();
renderGuildsCheckboxes();
}
} catch (e) { console.error(e); }
} catch (e) {}
}
async function addGuild(e) {
e.preventDefault();
const name = document.getElementById('newGuildName').value;
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?")) return;
await fetch(`${API_URL}/guilds/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
fetchGuilds();
}
// --- USUARIOS ---
async function fetchUsers() {
@@ -165,95 +222,78 @@
currentUsers = data.users;
renderUsersTable();
}
} catch (e) { console.error(e); }
} 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...";
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, // Puede ir vacío al editar
password: document.getElementById('uPass').value,
role: document.getElementById('uRole').value,
guilds: selectedGuilds
guilds: selectedGuilds,
zones: tempUserZones // Enviamos las zonas configuradas
};
const url = isEdit ? `${API_URL}/admin/users/${userId}` : `${API_URL}/admin/users`;
const method = isEdit ? 'PUT' : 'POST';
try {
const res = await fetch(url, {
method: method,
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 ? "Usuario actualizado" : "Usuario creado");
showToast(isEdit ? "Datos actualizados" : "Usuario creado");
resetUserForm();
fetchUsers();
} else {
showToast("❌ " + json.error, true);
}
} else { showToast("❌ " + json.error, true); }
} catch (e) { showToast("Error conexión", true); }
finally { btn.disabled = false; btn.innerText = isEdit ? "Actualizar Usuario" : "Guardar Usuario"; }
}
async function deleteUser(id) {
if(!confirm("¿Seguro que quieres borrar a este usuario?")) return;
try {
const res = await fetch(`${API_URL}/admin/users/${id}`, { method: 'DELETE', headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` } });
if(res.ok) { showToast("Usuario borrado"); fetchUsers(); }
} catch(e) { showToast("Error", true); }
finally { btn.disabled = false; btn.innerText = isEdit ? "Actualizar Datos" : "Guardar Usuario"; }
}
function editUser(id) {
const user = currentUsers.find(u => u.id === id);
if(!user) return;
// Rellenar form
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 = ""; // Limpiar pass
document.getElementById('uPass').placeholder = "Dejar en blanco para no cambiar";
document.getElementById('uPass').value = "";
tempUserZones = user.zones || []; // Cargamos zonas del usuario
renderTempZones();
// Marcar gremios
const userGuilds = user.guilds || [];
document.querySelectorAll('.guild-checkbox').forEach(cb => {
cb.checked = userGuilds.includes(parseInt(cb.value));
});
// Cambiar UI
document.getElementById('formTitle').innerText = "2. Editando Usuario";
document.getElementById('btnSubmitUser').innerText = "Actualizar Usuario";
document.getElementById('btnSubmitUser').classList.replace('bg-green-600', 'bg-blue-600');
document.getElementById('btnSubmitUser').classList.replace('hover:bg-green-700', 'hover:bg-blue-700');
document.getElementById('btnCancelEdit').classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function resetUserForm() {
document.getElementById('editUserId').value = "";
document.querySelector('form').reset();
document.querySelectorAll('input').forEach(i => i.value = "");
tempUserZones = [];
renderTempZones();
document.getElementById('formTitle').innerText = "2. Nuevo Usuario";
document.getElementById('btnSubmitUser').innerText = "Guardar Usuario";
document.getElementById('btnSubmitUser').classList.replace('bg-blue-600', 'bg-green-600');
document.getElementById('btnSubmitUser').classList.replace('hover:bg-blue-700', 'hover:bg-green-700');
document.getElementById('uPass').placeholder = "Opcional al editar";
document.getElementById('btnCancelEdit').classList.add('hidden');
renderGuildsCheckboxes(); // Limpiar checks
renderGuildsCheckboxes();
}
// --- RENDERS ---
@@ -261,47 +301,45 @@
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-sm font-medium">${g.name}</span><button onclick="deleteGuild(${g.id})" class="text-gray-400 hover:text-red-500"><i data-lucide="trash-2" class="w-4 h-4"></i></button></div>`;
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 onclick="deleteGuild(${g.id})" class="text-gray-300 hover:text-red-500 transition-colors"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i></button></div>`;
});
if(window.lucide) lucide.createIcons();
lucide.createIcons();
}
function renderGuildsCheckboxes() {
const area = document.getElementById('guildsCheckboxArea');
if (availableGuilds.length === 0) { area.innerHTML = '<p class="text-xs text-gray-400">Sin gremios.</p>'; return; }
area.innerHTML = "";
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-green-50 rounded border border-transparent hover:border-green-200"><input type="checkbox" value="${g.id}" class="guild-checkbox form-checkbox h-4 w-4 text-green-600 rounded"> <span class="text-sm font-medium">${g.name}</span></label>`;
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"><input type="checkbox" value="${g.id}" class="guild-checkbox h-4 w-4 text-green-600 border-gray-300 rounded"><span class="text-[10px] font-black uppercase text-slate-500">${g.name}</span></label>`;
});
}
function renderUsersTable() {
const tbody = document.getElementById('usersListBody');
tbody.innerHTML = "";
if(currentUsers.length === 0) { tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-gray-400">No hay usuarios registrados.</td></tr>`; return; }
tbody.innerHTML = currentUsers.length === 0 ? `<tr><td colspan="5" class="p-8 text-center text-gray-300 font-bold uppercase tracking-widest">Cargando equipo...</td></tr>` : "";
currentUsers.forEach(u => {
// Mapear IDs de gremios a nombres
const uGuildNames = (u.guilds || []).map(gid => {
const g = availableGuilds.find(ag => ag.id === gid);
return g ? g.name : null;
}).filter(Boolean).join(", ");
const uGuildNames = (u.guilds || []).map(gid => availableGuilds.find(ag => ag.id === gid)?.name).filter(Boolean).join(", ");
// Formatear visualmente las zonas
const uZonesHtml = (u.zones || []).map(z => `<span class="block text-[10px] font-bold text-blue-600">📍 ${z.city}: ${z.cps}</span>`).join("");
tbody.innerHTML += `
<tr class="bg-white hover:bg-gray-50 transition border-b last:border-0">
<td class="p-4 font-medium text-gray-800">${u.full_name}</td>
<td class="p-4 text-gray-600 flex flex-col"><span class="text-xs text-gray-400">Email:</span> ${u.email} <span class="text-xs text-gray-400 mt-1">Tel:</span> ${u.phone}</td>
<td class="p-4"><span class="bg-blue-100 text-blue-700 px-2 py-1 rounded text-xs font-bold uppercase">${u.role}</span></td>
<td class="p-4 text-gray-500 text-xs">${uGuildNames || '-'}</td>
<td class="p-4 text-right space-x-2">
<button onclick="editUser(${u.id})" class="text-blue-500 hover:text-blue-700 font-medium text-sm">Editar</button>
<button onclick="deleteUser(${u.id})" class="text-red-500 hover:text-red-700 font-medium text-sm">Borrar</button>
<tr class="bg-white hover:bg-gray-50 transition border-b">
<td class="p-4"><div class="flex flex-col"><span class="font-black text-slate-800 uppercase">${u.full_name}</span><span class="text-[9px] text-gray-400 font-bold tracking-tighter">${u.email}</span></div></td>
<td class="p-4 font-black text-green-600">${u.phone}</td>
<td class="p-4"><span class="bg-slate-100 text-slate-600 px-2 py-0.5 rounded text-[10px] font-black uppercase">${u.role}</span><p class="text-[9px] text-gray-400 mt-1 uppercase font-bold">${uGuildNames || '-'}</p></td>
<td class="p-4">${uZonesHtml || '<span class="text-[9px] text-gray-300 italic">Sin zona</span>'}</td>
<td class="p-4 text-right space-x-3">
<button onclick="editUser(${u.id})" class="text-blue-500 hover:text-blue-700 font-black text-xs uppercase tracking-widest">Editar</button>
<button onclick="deleteUser(${u.id})" class="text-red-400 hover:text-red-700 font-black text-xs uppercase tracking-widest">Baja</button>
</td>
</tr>
`;
</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-lg shadow-2xl transition-all duration-300 z-50 flex items-center gap-3 ${err?'bg-red-600':'bg-slate-800'} text-white`;
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);
}