Actualizar usuarios.html

This commit is contained in:
2026-02-24 07:42:24 +00:00
parent 8c03751b15
commit ad5b4d6d55

View File

@@ -23,6 +23,15 @@
.text-primary-dynamic { color: var(--primary) !important; }
.bg-primary-dynamic { background-color: var(--primary) !important; }
.border-primary-dynamic { border-color: var(--primary) !important; }
/* Toggle Switch Custom */
.toggle-checkbox:checked {
right: 0;
border-color: #10b981; /* Verde esmeralda */
}
.toggle-checkbox:checked + .toggle-label {
background-color: #10b981;
}
</style>
</head>
<body class="text-slate-800 font-sans antialiased text-left">
@@ -79,10 +88,9 @@
</div>
<div class="flex gap-4 text-left">
<div class="w-1/2">
<label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Rol / Permisos</label>
<select id="uRole" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 outline-none font-bold text-xs transition-all shadow-inner uppercase tracking-wider text-slate-600 appearance-none cursor-pointer">
<option value="operario">Op. Normal (Puede coger de la bolsa)</option>
<option value="operario_cerrado">Op. Cerrado (Solo asignados por oficina)</option>
<label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Perfil Base</label>
<select id="uRole" onchange="toggleBolsaSwitch()" class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 outline-none font-bold text-xs transition-all shadow-inner uppercase tracking-wider text-slate-600 appearance-none cursor-pointer">
<option value="operario">Operario (App)</option>
<option value="facturacion">Facturación / Oficina</option>
<option value="admin">Administrador</option>
</select>
@@ -95,6 +103,17 @@
</div>
</div>
<div id="bolsaSwitchContainer" class="p-4 bg-emerald-50/50 border border-emerald-100 rounded-2xl flex items-center justify-between shadow-inner transition-all">
<div>
<h4 class="text-sm font-black text-emerald-800">Acceso a Bolsa Libre (Solicitar Servicios)</h4>
<p class="text-[10px] text-emerald-600 font-bold mt-0.5">Si lo desactivas, este operario solo verá los avisos que la oficina le asigne a dedo.</p>
</div>
<div class="relative inline-block w-12 mr-2 align-middle select-none transition duration-200 ease-in">
<input type="checkbox" name="toggle" id="uBolsaAccess" checked class="toggle-checkbox absolute block w-6 h-6 rounded-full bg-white border-4 border-slate-300 appearance-none cursor-pointer transition-all duration-300 z-10 top-0 left-0"/>
<label for="uBolsaAccess" class="toggle-label block overflow-hidden h-6 rounded-full bg-slate-300 cursor-pointer transition-colors duration-300"></label>
</div>
</div>
<div class="pt-4 text-left border-t border-slate-100">
<label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-3 ml-1 flex items-center gap-1.5"><i data-lucide="hammer" class="w-3 h-3 text-emerald-500"></i> Gremios Asignados</label>
<div class="p-4 border border-slate-200 rounded-2xl bg-slate-50 grid grid-cols-2 md:grid-cols-4 gap-3 text-left shadow-inner" id="guildsCheckboxArea"></div>
@@ -112,12 +131,12 @@
</div>
<div class="relative text-left">
<label class="block text-[9px] font-black text-primary-dynamic mb-1.5 uppercase tracking-widest text-left">2. Municipio</label>
<select id="selMunicipio" onchange="autoFillCP(this.value)" class="w-full text-xs font-bold p-3.5 border border-primary-dynamic/30 rounded-xl outline-none focus:ring-2 focus:ring-primary-dynamic/40 bg-white disabled:opacity-50 cursor-pointer shadow-sm text-slate-700" disabled>
<select id="selMunicipio" onchange="handleMunicipioChange(this.value)" class="w-full text-xs font-bold p-3.5 border border-primary-dynamic/30 rounded-xl outline-none focus:ring-2 focus:ring-primary-dynamic/40 bg-white disabled:opacity-50 cursor-pointer shadow-sm text-slate-700" disabled>
<option value="">-- Elige Municipio --</option>
</select>
<div id="loaderMun" class="hidden absolute right-10 top-11"><i data-lucide="loader-2" class="w-4 h-4 animate-spin text-primary-dynamic"></i></div>
</div>
<div class="text-left">
<div class="text-left relative">
<label class="block text-[9px] font-black text-primary-dynamic mb-1.5 uppercase tracking-widest text-left">3. Código(s) Postal(es)</label>
<div class="flex gap-2 text-left">
<input type="text" id="cpInput" placeholder="Ej: 11201-11207" class="flex-1 text-xs font-black p-3.5 border border-primary-dynamic/30 rounded-xl outline-none focus:ring-2 focus:ring-primary-dynamic/40 bg-white text-primary-dynamic shadow-inner">
@@ -125,6 +144,7 @@
<i data-lucide="plus" class="w-5 h-5"></i>
</button>
</div>
<input type="hidden" id="hiddenManualCity" value="">
</div>
</div>
<div id="userZonesArea" class="flex flex-wrap gap-2 min-h-[60px] p-4 bg-white rounded-[1.5rem] border border-primary-dynamic/20 shadow-inner text-left"></div>
@@ -150,7 +170,7 @@
<tr class="bg-white text-slate-400 text-[10px] font-black uppercase tracking-[0.2em] border-b border-slate-100 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">Rol / Permisos</th>
<th class="p-4">Zonas Cobertura</th>
<th class="p-4 text-right">Acciones</th>
</tr>
@@ -204,6 +224,17 @@
setupProvinceSelect();
});
// Oculta/Muestra el interruptor de la bolsa según el rol seleccionado
function toggleBolsaSwitch() {
const role = document.getElementById('uRole').value;
const container = document.getElementById('bolsaSwitchContainer');
if(role === 'operario') {
container.style.display = 'flex';
} else {
container.style.display = 'none';
}
}
function setupProvinceSelect() {
const sel = document.getElementById('selProvince');
if(!sel) return;
@@ -221,6 +252,8 @@
const loader = document.getElementById('loaderMun');
selMun.innerHTML = '<option value="">-- Cargando... --</option>';
selMun.disabled = true;
document.getElementById('hiddenManualCity').value = ""; // Reset
if(!provName) return;
if (loader) loader.classList.remove('hidden');
@@ -244,10 +277,10 @@
opt.innerText = `${mun.toUpperCase()} (${grouped[mun].length} CPs)`;
selMun.appendChild(opt);
});
selMun.innerHTML += '<option value="OTRO">-- NO ESTÁ EN LA LISTA (MANUAL) --</option>';
selMun.innerHTML += '<option value="OTRO">-- ✍️ ESCRIBIR MANUALMENTE --</option>';
selMun.disabled = false;
} else {
selMun.innerHTML = '<option value="OTRO">-- ESCRIBIR MANUALMENTE --</option>';
selMun.innerHTML = '<option value="OTRO">-- ✍️ ESCRIBIR MANUALMENTE --</option>';
selMun.disabled = false;
}
} catch (e) {
@@ -258,39 +291,56 @@
}
}
function autoFillCP(munName) {
const sel = document.getElementById('selMunicipio');
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);
function handleMunicipioChange(val) {
if (val === "OTRO") {
const customMun = prompt("Nombre de la población / zona:");
if (customMun && customMun.trim() !== "") {
// Guardamos el nombre real en el input oculto en lugar de dejar la palabra "OTRO"
document.getElementById('hiddenManualCity').value = customMun.toUpperCase();
// Cambiamos el texto visual del select para que sepa que está seleccionada
document.getElementById('selMunicipio').options[document.getElementById('selMunicipio').selectedIndex].text = `✔️ ${customMun.toUpperCase()}`;
showToast("Ahora escribe los CPs abajo", false);
} else {
// Si cancela, volvemos a la opción por defecto
document.getElementById('selMunicipio').value = "";
}
} else {
document.getElementById('hiddenManualCity').value = "";
}
}
function addZoneToUser() {
const prov = document.getElementById('selProvince').value;
const selMun = document.getElementById('selMunicipio');
const munName = selMun.value;
const munValue = selMun.value;
const manualCityName = document.getElementById('hiddenManualCity').value;
if (!prov || !munName) { showToast("Selecciona Provincia y Municipio", true); return; }
if (!prov || !munValue) { showToast("Selecciona Provincia y Municipio", true); return; }
if (munName === "OTRO" || (selMun.options[selMun.selectedIndex] && selMun.options[selMun.selectedIndex].text.includes("MANUAL"))) {
if (munValue === "OTRO") {
const manualCP = document.getElementById('cpInput').value.trim();
if(!manualCP) { showToast("Escribe el CP manual", true); return; }
tempUserZones.push({ province: prov, city: munName === "OTRO" ? "MANUAL" : munName, cps: manualCP });
} else {
const cpList = JSON.parse(selMun.options[selMun.selectedIndex].dataset.cps);
cpList.forEach(cp => {
if (!tempUserZones.some(z => z.city === munName && z.cps === cp)) {
tempUserZones.push({ province: prov, city: munName, cps: cp });
if(!manualCP) { showToast("Escribe el CP manual en el cuadro", true); return; }
if(!manualCityName) { showToast("Falta el nombre de la población", true); return; }
// Si ha puesto varios separados por coma o guion
const cpsArray = manualCP.split(/[,-\s]+/).filter(c => c.trim() !== "");
cpsArray.forEach(cp => {
if (!tempUserZones.some(z => z.city === manualCityName && z.cps === cp)) {
tempUserZones.push({ province: prov, city: manualCityName, cps: cp });
}
});
showToast(`Añadidos códigos de ${munName}`);
showToast(`Zonas manuales añadidas`);
} else {
// Modo Automático desde la lista
const cpList = JSON.parse(selMun.options[selMun.selectedIndex].dataset.cps);
cpList.forEach(cp => {
if (!tempUserZones.some(z => z.city === munValue && z.cps === cp)) {
tempUserZones.push({ province: prov, city: munValue, cps: cp });
}
});
showToast(`Añadidos códigos de ${munValue}`);
}
renderTempZones();
document.getElementById('cpInput').value = "";
@@ -364,12 +414,20 @@
lucide.createIcons();
const selectedGuilds = Array.from(document.querySelectorAll('.guild-checkbox:checked')).map(cb => cb.value);
// Lógica del rol final según el interruptor
let finalRole = document.getElementById('uRole').value;
if (finalRole === 'operario') {
const wantsBolsa = document.getElementById('uBolsaAccess').checked;
if (!wantsBolsa) finalRole = 'operario_cerrado';
}
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,
role: finalRole,
guilds: selectedGuilds,
zones: tempUserZones
};
@@ -395,12 +453,22 @@
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;
// Setear el select del rol base
let baseRole = user.role;
if (baseRole === 'operario_cerrado') baseRole = 'operario';
document.getElementById('uRole').value = baseRole;
toggleBolsaSwitch(); // Muestra el interruptor si es operario
// Setear el interruptor
document.getElementById('uBolsaAccess').checked = (user.role === 'operario');
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('btnCancelEdit').classList.remove('hidden');
window.scrollTo({ top: 0, behavior: 'smooth' });
@@ -420,7 +488,10 @@
document.getElementById('uEmail').value = "";
document.getElementById('uPhone').value = "";
document.getElementById('uPass').value = "";
document.getElementById('uRole').value = "operario"; // Reset al valor por defecto
document.getElementById('uRole').value = "operario";
document.getElementById('uBolsaAccess').checked = true;
toggleBolsaSwitch();
tempUserZones = [];
renderTempZones();
document.getElementById('formTitle').innerText = "2. Nueva Ficha de Usuario";
@@ -464,27 +535,20 @@
return `<div class="mb-1.5 last:mb-0"><span class="font-black ${isActive ? 'text-primary-dynamic' : 'text-slate-400'} text-[10px] uppercase tracking-wider"><i data-lucide="map-pin" class="w-3 h-3 inline"></i> ${city}</span> <span class="text-slate-500 text-[9px] font-bold">(${groupedZones[city].join(", ")})</span></div>`;
}).join("") || '<span class="text-[9px] text-slate-400 font-bold italic">Sin zona</span>';
let roleBadge = "OP. NORMAL";
let roleBadge = "OP. APP (BOLSA LIBRE)";
let roleColor = "bg-blue-50 text-blue-600 border-blue-100";
let toggleRoleBtnText = "Bolsa Off"; // Botón para cambiar rol
if (u.role === 'operario_cerrado') {
roleBadge = "OP. CERRADO";
roleBadge = "OP. CERRADO (SOLO ASIGNADOS)";
roleColor = "bg-amber-50 text-amber-600 border-amber-200";
toggleRoleBtnText = "Bolsa On";
} else if (u.role === 'admin') {
roleBadge = "ADMINISTRADOR";
roleColor = "bg-purple-50 text-purple-600 border-purple-200";
toggleRoleBtnText = ""; // Los admin no tienen esto
} else if (u.role === 'facturacion') {
roleBadge = "FACTURACIÓN";
roleColor = "bg-emerald-50 text-emerald-600 border-emerald-200";
toggleRoleBtnText = "";
}
// Generar el botón de alternar bolsa si aplica
const toggleRoleHtml = toggleRoleBtnText ? `<button onclick="toggleUserRole(${u.id}, '${u.role}')" class="text-purple-600 hover:text-white hover:bg-purple-600 border-purple-200 font-black text-[9px] uppercase tracking-widest border px-3 py-1.5 rounded-lg transition-all shadow-sm">${toggleRoleBtnText}</button>` : '';
tbody.innerHTML += `
<tr class="${isActive ? 'bg-white' : 'bg-slate-50 opacity-70'} hover:bg-slate-50/80 transition-colors border-b border-slate-100">
<td class="p-4">
@@ -504,7 +568,6 @@
</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-2">
${toggleRoleHtml}
<button onclick="editUser(${u.id})" class="text-blue-500 hover:text-white hover:bg-blue-500 font-black text-[9px] uppercase tracking-widest border border-blue-200 px-3 py-1.5 rounded-lg transition-all shadow-sm">Editar</button>
<button onclick="toggleUserStatus(${u.id}, '${u.status || 'active'}')" class="${isActive ? 'text-amber-600 hover:bg-amber-500 hover:text-white border-amber-200' : 'text-emerald-600 hover:bg-emerald-500 hover:text-white border-emerald-200'} font-black text-[9px] uppercase tracking-widest border px-3 py-1.5 rounded-lg transition-all shadow-sm">
${isActive ? 'Pausar' : 'Activar'}
@@ -516,44 +579,6 @@
lucide.createIcons();
}
// Nueva función para alternar rápidamente el rol de un operario
async function toggleUserRole(id, currentRole) {
const newRole = currentRole === 'operario' ? 'operario_cerrado' : 'operario';
const msg = newRole === 'operario_cerrado' ? "¿Quitar acceso a la Bolsa Libre a este operario?" : "¿Devolver acceso a la Bolsa Libre a este operario?";
if(!confirm(msg)) return;
// Recogemos el usuario para enviar el objeto completo (el endpoint PUT lo requiere)
const user = currentUsers.find(u => u.id === id);
if (!user) return;
const data = {
fullName: user.full_name,
email: user.email,
phone: user.phone,
role: newRole,
guilds: user.guilds || [],
zones: user.zones || []
};
try {
const res = await fetch(`${API_URL}/admin/users/${id}`, {
method: 'PUT',
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${localStorage.getItem("token")}`
},
body: JSON.stringify(data)
});
const json = await res.json();
if(json.ok) {
showToast(newRole === 'operario_cerrado' ? "Acceso a bolsa denegado" : "Acceso a bolsa permitido");
fetchUsers();
} else {
showToast("Error al cambiar permisos", true);
}
} catch(e) { showToast("Error de conexión", true); }
}
async function toggleUserStatus(id, currentStatus) {
const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
const msg = newStatus === 'active' ? "¿Reactivar operario para que reciba avisos?" : "¿Dar de baja temporal? (No verá avisos)";