646 lines
41 KiB
HTML
646 lines
41 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>
|
|
/* VARIABLES CORPORATIVAS DINÁMICAS */
|
|
:root {
|
|
--primary: #2563eb;
|
|
--secondary: #10b981;
|
|
--app-bg: #f8fafc;
|
|
}
|
|
|
|
body { background-color: var(--app-bg); }
|
|
.fade-in { animation: fadeIn 0.5s ease-in-out; }
|
|
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
|
.no-scrollbar::-webkit-scrollbar { display: none; }
|
|
|
|
/* Clases CSS dinámicas para aplicar las variables */
|
|
.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 {
|
|
transform: translateX(100%);
|
|
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">
|
|
|
|
<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 p-8 fade-in relative z-10">
|
|
<h2 class="text-2xl font-black text-slate-800 mb-8 text-left tracking-tight">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-[2rem] shadow-sm border border-slate-100">
|
|
<div class="flex items-center gap-3 mb-4 text-primary-dynamic text-left">
|
|
<i data-lucide="hammer" class="w-6 h-6"></i>
|
|
<h3 class="text-lg font-black text-slate-800 tracking-tight">1. Gremios / Especialidades</h3>
|
|
</div>
|
|
<div class="flex flex-col md:flex-row gap-6 text-left">
|
|
<form onsubmit="addGuild(event)" class="flex gap-3 h-12 w-full md:w-1/2 text-left">
|
|
<input type="text" id="newGuildName" placeholder="NUEVO GREMIO (EJ. LIMPIEZA)" required class="flex-1 px-4 py-3 border border-slate-200 rounded-xl outline-none text-sm font-bold uppercase transition-all bg-slate-50 focus:border-blue-500 focus:ring-2 focus:ring-blue-200">
|
|
<button type="submit" class="bg-primary-dynamic text-white px-5 rounded-xl hover:opacity-90 font-black shadow-md transition-all active:scale-95 flex items-center justify-center"><i data-lucide="plus" class="w-5 h-5"></i></button>
|
|
</form>
|
|
<div class="w-full md:w-1/2 border border-slate-200 rounded-xl bg-slate-50 p-3 max-h-40 overflow-y-auto space-y-2 no-scrollbar" id="guildsList"></div>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="w-full bg-white p-8 rounded-[2rem] shadow-sm border border-slate-100 relative text-left">
|
|
<button onclick="resetUserForm()" id="btnCancelEdit" class="hidden absolute top-8 right-8 text-xs text-rose-500 hover:text-rose-600 font-black uppercase tracking-widest bg-rose-50 px-3 py-1.5 rounded-lg transition-colors border border-rose-100">Cancelar Edición</button>
|
|
|
|
<div class="flex items-center gap-3 mb-6 text-emerald-600 text-left">
|
|
<i data-lucide="user-plus" class="w-6 h-6"></i>
|
|
<h3 class="text-lg font-black text-slate-800 tracking-tight" 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-[10px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Nombre Completo</label>
|
|
<input type="text" id="uName" required 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-sm transition-all shadow-inner">
|
|
</div>
|
|
<div>
|
|
<label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Correo Electrónico</label>
|
|
<input type="email" id="uEmail" required 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-sm transition-all shadow-inner">
|
|
</div>
|
|
</div>
|
|
<div class="space-y-4">
|
|
<div>
|
|
<label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Teléfono</label>
|
|
<input type="tel" id="uPhone" required placeholder="+34 600..." 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-black text-emerald-700 text-sm transition-all shadow-inner">
|
|
</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">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>
|
|
</div>
|
|
<div class="w-1/2">
|
|
<label class="block text-[10px] font-black text-slate-400 uppercase tracking-widest mb-1.5 ml-1">Contraseña</label>
|
|
<input type="password" id="uPass" 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-sm transition-all shadow-inner" placeholder="••••••••">
|
|
</div>
|
|
</div>
|
|
</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>
|
|
</div>
|
|
|
|
<div class="pt-4 text-left border-t border-slate-100">
|
|
<label class="block text-[10px] font-black text-primary-dynamic uppercase mb-3 tracking-widest text-left flex items-center gap-1.5"><i data-lucide="map" class="w-3 h-3"></i> Cobertura Geográfica (Toda España)</label>
|
|
<div class="bg-primary-dynamic/5 border-2 border-primary-dynamic/20 rounded-[1.5rem] p-6 space-y-5 text-left">
|
|
<div class="grid grid-cols-1 md:grid-cols-3 gap-4 text-left">
|
|
<div>
|
|
<label class="block text-[9px] font-black text-primary-dynamic mb-1.5 uppercase tracking-widest">1. Provincia</label>
|
|
<select id="selProvince" onchange="fetchMunicipios(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 cursor-pointer shadow-sm text-slate-700">
|
|
<option value="">-- Seleccionar --</option>
|
|
</select>
|
|
</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="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 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">
|
|
<button type="button" onclick="addZoneToUser()" class="bg-primary-dynamic text-white px-5 rounded-xl font-black hover:opacity-90 transition-all shadow-md active:scale-95 flex items-center justify-center">
|
|
<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>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="pt-6 text-left">
|
|
<button type="submit" id="btnSubmitUser" class="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-black py-4 rounded-[1.5rem] transition-all shadow-lg shadow-emerald-500/30 uppercase tracking-widest text-xs text-left justify-center flex items-center gap-2 active:scale-95">
|
|
<i data-lucide="save" class="w-4 h-4"></i> Guardar Usuario y Zonas
|
|
</button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
|
|
<div class="w-full bg-white rounded-[2rem] shadow-sm border border-slate-100 overflow-hidden text-left mb-10">
|
|
<div class="p-6 border-b border-slate-100 bg-slate-50 text-left flex items-center gap-2">
|
|
<i data-lucide="users" class="w-5 h-5 text-slate-400"></i>
|
|
<h3 class="font-black text-slate-800 uppercase tracking-tight">Listado de Equipo</h3>
|
|
</div>
|
|
<div class="overflow-x-auto no-scrollbar text-left p-2">
|
|
<table class="w-full text-left border-collapse">
|
|
<thead>
|
|
<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 / Permisos</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-slate-50 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-xl shadow-2xl transform translate-y-20 opacity-0 transition-all duration-300 z-50 flex items-center gap-3 font-bold text-xs uppercase tracking-widest"><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"];
|
|
|
|
// --- SISTEMA DE TEMA DINÁMICO ---
|
|
async function applyTheme() {
|
|
try {
|
|
let theme = JSON.parse(localStorage.getItem('app_theme'));
|
|
const res = await fetch(`${API_URL}/config/company`, {
|
|
headers: { "Authorization": `Bearer ${localStorage.getItem("token")}` }
|
|
});
|
|
const data = await res.json();
|
|
if(data.ok && data.config && data.config.portal_settings && data.config.portal_settings.app_settings) {
|
|
theme = data.config.portal_settings.app_settings;
|
|
localStorage.setItem('app_theme', JSON.stringify(theme));
|
|
}
|
|
if(theme) {
|
|
document.documentElement.style.setProperty('--primary', theme.primary);
|
|
document.documentElement.style.setProperty('--secondary', theme.secondary);
|
|
document.documentElement.style.setProperty('--app-bg', theme.bg);
|
|
}
|
|
} catch (e) { console.warn("Usando tema por defecto"); }
|
|
}
|
|
|
|
document.addEventListener("DOMContentLoaded", async () => {
|
|
if (!localStorage.getItem("token")) { window.location.href = "index.html"; return; }
|
|
await applyTheme();
|
|
lucide.createIcons();
|
|
fetchGuilds();
|
|
fetchUsers();
|
|
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;
|
|
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);
|
|
});
|
|
}
|
|
|
|
async function fetchMunicipios(provName) {
|
|
const selMun = document.getElementById('selMunicipio');
|
|
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');
|
|
|
|
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) {
|
|
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;
|
|
opt.dataset.cps = JSON.stringify(grouped[mun]);
|
|
opt.innerText = `${mun.toUpperCase()} (${grouped[mun].length} CPs)`;
|
|
selMun.appendChild(opt);
|
|
});
|
|
selMun.innerHTML += '<option value="OTRO">-- ✍️ ESCRIBIR MANUALMENTE --</option>';
|
|
selMun.disabled = false;
|
|
} else {
|
|
selMun.innerHTML = '<option value="OTRO">-- ✍️ ESCRIBIR MANUALMENTE --</option>';
|
|
selMun.disabled = false;
|
|
}
|
|
} catch (e) {
|
|
console.error("Error geo:", e);
|
|
showToast("Error base de datos", true);
|
|
} finally {
|
|
if (loader) loader.classList.add('hidden');
|
|
}
|
|
}
|
|
|
|
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 munValue = selMun.value;
|
|
const manualCityName = document.getElementById('hiddenManualCity').value;
|
|
const manualCP = document.getElementById('cpInput').value.trim();
|
|
|
|
if (!prov || !munValue) { showToast("Selecciona Provincia y Municipio", true); return; }
|
|
|
|
// Determinamos el nombre real de la ciudad (el de la lista o el que escribió a mano)
|
|
const finalCityName = munValue === "OTRO" ? manualCityName : munValue;
|
|
|
|
if (munValue === "OTRO" && !manualCityName) {
|
|
showToast("Falta el nombre de la población", true); return;
|
|
}
|
|
|
|
// ESCENARIO 1: Ha escrito ALGO en la caja (rangos, números sueltos...)
|
|
if (manualCP !== "") {
|
|
let cpsArray = [];
|
|
// Cortamos por comas o espacios
|
|
const partes = manualCP.split(/[, \n]+/).filter(c => c.trim() !== "");
|
|
|
|
partes.forEach(parte => {
|
|
if (parte.includes('-')) {
|
|
const [start, end] = parte.split('-');
|
|
const numStart = parseInt(start, 10);
|
|
const numEnd = parseInt(end, 10);
|
|
|
|
// Si es un rango válido, extraemos todos los números del medio
|
|
if (!isNaN(numStart) && !isNaN(numEnd) && numStart <= numEnd) {
|
|
for (let i = numStart; i <= numEnd; i++) {
|
|
cpsArray.push(String(i).padStart(5, '0')); // Mantiene los ceros a la izquierda
|
|
}
|
|
} else {
|
|
cpsArray.push(parte); // Fallback por si lo escribe mal
|
|
}
|
|
} else {
|
|
cpsArray.push(parte); // Si es un número normal sin guiones
|
|
}
|
|
});
|
|
|
|
let addedCount = 0;
|
|
cpsArray.forEach(cp => {
|
|
if (!tempUserZones.some(z => z.city === finalCityName && z.cps === cp)) {
|
|
tempUserZones.push({ province: prov, city: finalCityName, cps: cp });
|
|
addedCount++;
|
|
}
|
|
});
|
|
|
|
if(addedCount > 0) showToast(`Se han añadido ${addedCount} códigos postales`);
|
|
else showToast("Esos códigos ya estaban añadidos");
|
|
|
|
}
|
|
// ESCENARIO 2: No ha escrito nada en la caja, pero eligió una ciudad de la lista
|
|
else if (munValue !== "OTRO") {
|
|
const cpList = JSON.parse(selMun.options[selMun.selectedIndex].dataset.cps || "[]");
|
|
let addedCount = 0;
|
|
cpList.forEach(cp => {
|
|
if (!tempUserZones.some(z => z.city === munValue && z.cps === cp)) {
|
|
tempUserZones.push({ province: prov, city: munValue, cps: cp });
|
|
addedCount++;
|
|
}
|
|
});
|
|
|
|
if(addedCount > 0) showToast(`Añadidos ${addedCount} códigos de ${munValue}`);
|
|
else showToast("Esos códigos ya estaban añadidos");
|
|
}
|
|
else {
|
|
showToast("Escribe el CP en el cuadro", true); return;
|
|
}
|
|
|
|
renderTempZones();
|
|
document.getElementById('cpInput').value = "";
|
|
}
|
|
|
|
function renderTempZones() {
|
|
const area = document.getElementById('userZonesArea');
|
|
if(!area) return;
|
|
area.innerHTML = tempUserZones.length === 0 ? '<p class="text-[10px] text-slate-400 italic p-1 font-bold">Sin zonas añadidas...</p>' : "";
|
|
|
|
const visualGroup = tempUserZones.reduce((acc, curr) => {
|
|
if(!acc[curr.city]) acc[curr.city] = [];
|
|
acc[curr.city].push(curr.cps);
|
|
return acc;
|
|
}, {});
|
|
|
|
Object.keys(visualGroup).forEach(city => {
|
|
area.innerHTML += `
|
|
<span class="bg-primary-dynamic/10 text-primary-dynamic px-3 py-1.5 rounded-lg text-[10px] font-black border border-primary-dynamic/20 flex items-center gap-2 shadow-sm">
|
|
${city} (${visualGroup[city].length} CPs)
|
|
<button type="button" onclick="removeTempCity('${city}')" class="text-primary-dynamic hover:text-red-500 transition-colors"><i data-lucide="x" class="w-3.5 h-3.5"></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.innerHTML = '<i data-lucide="loader-2" class="w-4 h-4 animate-spin"></i> PROCESANDO...';
|
|
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: finalRole,
|
|
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 ? "Usuario Actualizado" : "Usuario Creado"); resetUserForm(); fetchUsers(); }
|
|
else { showToast("Error: " + json.error, true); }
|
|
} catch (e) { showToast("Error conexión", true); }
|
|
finally { btn.disabled = false; btn.innerHTML = isEdit ? '<i data-lucide="save" class="w-4 h-4"></i> Actualizar Datos' : '<i data-lucide="save" class="w-4 h-4"></i> Guardar Usuario y Zonas'; lucide.createIcons(); }
|
|
}
|
|
|
|
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;
|
|
|
|
// 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' });
|
|
}
|
|
|
|
async function deleteUser(id) {
|
|
if(!confirm("¿Borrar usuario definitivamente?")) 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 = "";
|
|
document.getElementById('uRole').value = "operario";
|
|
document.getElementById('uBolsaAccess').checked = true;
|
|
toggleBolsaSwitch();
|
|
|
|
tempUserZones = [];
|
|
renderTempZones();
|
|
document.getElementById('formTitle').innerText = "2. Nueva Ficha de Usuario";
|
|
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.5 rounded-xl border border-slate-100 shadow-sm"><span class="text-[10px] font-black uppercase tracking-widest text-slate-700">${g.name}</span><button onclick="deleteGuild(${g.id})" class="text-slate-300 hover:text-red-500 transition-colors p-1 bg-slate-50 rounded-md"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i></button></div>`;
|
|
});
|
|
lucide.createIcons();
|
|
}
|
|
|
|
function renderGuildsCheckboxes() {
|
|
const area = document.getElementById('guildsCheckboxArea');
|
|
area.innerHTML = availableGuilds.length === 0 ? '<p class="text-xs text-slate-400 italic">No hay gremios...</p>' : "";
|
|
availableGuilds.forEach(g => {
|
|
area.innerHTML += `<label class="flex items-center space-x-2 cursor-pointer p-2.5 hover:bg-emerald-50 rounded-xl border border-transparent hover:border-emerald-200 transition-all"><input type="checkbox" value="${g.id}" class="guild-checkbox h-4 w-4 text-emerald-600 border-slate-300 rounded focus:ring-emerald-500"><span class="text-[10px] font-black uppercase tracking-widest text-slate-600">${g.name}</span></label>`;
|
|
});
|
|
}
|
|
|
|
function renderUsersTable() {
|
|
const tbody = document.getElementById('usersListBody');
|
|
if (!tbody) return;
|
|
tbody.innerHTML = currentUsers.length === 0 ? `<tr><td colspan="5" class="p-8 text-center text-slate-400 font-black uppercase tracking-widest text-xs">Cargando equipo...</td></tr>` : "";
|
|
|
|
currentUsers.forEach(u => {
|
|
const isActive = u.status === 'active';
|
|
const uGuildNames = (u.guilds || []).map(gid => availableGuilds.find(ag => ag.id === gid)?.name).filter(Boolean).join(", ");
|
|
|
|
const groupedZones = (u.zones || []).reduce((acc, curr) => {
|
|
if (!acc[curr.city]) acc[curr.city] = [];
|
|
if (!acc[curr.city].includes(curr.cps)) acc[curr.city].push(curr.cps);
|
|
return acc;
|
|
}, {});
|
|
|
|
const uZonesHtml = Object.keys(groupedZones).map(city => {
|
|
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. APP (BOLSA LIBRE)";
|
|
let roleColor = "bg-blue-50 text-blue-600 border-blue-100";
|
|
|
|
if (u.role === 'operario_cerrado') {
|
|
roleBadge = "OP. CERRADO (SOLO ASIGNADOS)";
|
|
roleColor = "bg-amber-50 text-amber-600 border-amber-200";
|
|
} else if (u.role === 'admin') {
|
|
roleBadge = "ADMINISTRADOR";
|
|
roleColor = "bg-purple-50 text-purple-600 border-purple-200";
|
|
} else if (u.role === 'facturacion') {
|
|
roleBadge = "FACTURACIÓN";
|
|
roleColor = "bg-emerald-50 text-emerald-600 border-emerald-200";
|
|
}
|
|
|
|
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">
|
|
<div class="flex flex-col">
|
|
<div class="flex items-center gap-2">
|
|
${!isActive ? '<i data-lucide="lock" class="w-3.5 h-3.5 text-rose-500"></i>' : '<div class="w-2 h-2 rounded-full bg-emerald-500"></div>'}
|
|
<span class="font-black ${isActive ? 'text-slate-800' : 'text-slate-500'} uppercase text-xs">${u.full_name}</span>
|
|
</div>
|
|
<span class="text-[10px] text-slate-400 font-bold mt-1">${u.email}</span>
|
|
${!isActive ? '<span class="text-[8px] font-black text-rose-500 mt-1.5 uppercase tracking-widest bg-rose-50 px-2 py-0.5 rounded-md w-max border border-rose-100">[ Baja Temporal ]</span>' : ''}
|
|
</div>
|
|
</td>
|
|
<td class="p-4 font-black ${isActive ? 'text-emerald-600' : 'text-slate-400'} text-xs">${u.phone}</td>
|
|
<td class="p-4">
|
|
<span class="${!isActive ? 'bg-slate-200 text-slate-500 border-slate-300' : roleColor} px-2.5 py-1 rounded-lg text-[9px] font-black uppercase tracking-widest border">${roleBadge}</span>
|
|
<p class="text-[9px] text-slate-500 mt-2 uppercase font-bold tracking-wider leading-tight">${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-2">
|
|
<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'}
|
|
</button>
|
|
<button onclick="deleteUser(${u.id})" class="text-rose-500 hover:bg-rose-500 hover:text-white font-black text-[9px] uppercase tracking-widest border border-rose-200 px-3 py-1.5 rounded-lg transition-all shadow-sm">Borrar</button>
|
|
</td>
|
|
</tr>`;
|
|
});
|
|
lucide.createIcons();
|
|
}
|
|
|
|
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)";
|
|
if(!confirm(msg)) return;
|
|
|
|
try {
|
|
const res = await fetch(`${API_URL}/admin/users/${id}/status`, {
|
|
method: 'PATCH',
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Authorization": `Bearer ${localStorage.getItem("token")}`
|
|
},
|
|
body: JSON.stringify({ status: newStatus })
|
|
});
|
|
const data = await res.json();
|
|
if(data.ok) {
|
|
showToast(newStatus === 'active' ? "Operario activado" : "Operario en baja");
|
|
fetchUsers();
|
|
}
|
|
} catch(e) { showToast("Error de conexión", true); }
|
|
}
|
|
|
|
function showToast(msg, err=false){
|
|
const t=document.getElementById('toast'), m=document.getElementById('toastMsg');
|
|
t.className=`fixed bottom-5 right-5 px-6 py-4 rounded-2xl shadow-2xl transition-all duration-300 z-50 flex items-center gap-3 font-bold text-xs uppercase tracking-widest ${err?'bg-rose-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> |