Files
soft_usite/resources/views/users.html
T
Lizandro GuarnizoandClaude Sonnet 4.6 107178aa97 feat(users): reemplazar confirmación por envío de credenciales con link de reset
- Eliminar envío automático de confirmación al crear usuario
- Nuevo botón en cada fila: enviar credenciales (usuario + link establecer contraseña)
- POST /app/users/:id/credenciales → SendUserCredencialesEmail
- Email incluye username, link al login y link para establecer contraseña

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-06 21:57:36 -05:00

565 lines
31 KiB
HTML
Executable File

<!-- Container Principal -->
<div x-data="modals" @keydown.escape="closeModal" class="bg-white rounded-lg shadow">
<div class="container mx-auto p-6 w-full">
<!-- Page header -->
<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 mb-6">
<div>
<h1 class="text-2xl font-bold">Usuarios</h1>
<p class="text-xs text-slate-500 mt-0.5">Gestión de usuarios del sistema</p>
</div>
<div class="flex items-center gap-3">
<!-- Búsqueda -->
<div class="relative">
<div class="absolute left-2.5 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"/>
</svg>
</div>
<input type="text" x-model="searchQuery" placeholder="Buscar..."
class="border border-gray-300 rounded w-full md:w-56" @input="loadRegister()">
<div x-show="isLoading" class="absolute right-2.5 top-1/2 -translate-y-1/2">
<svg class="animate-spin h-3.5 w-3.5 text-slate-400" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
</svg>
</div>
</div>
<!-- Nuevo -->
<button class="flex items-center gap-2 text-white text-sm font-medium px-4 py-2 rounded-lg transition-colors"
style="background-color:#8eb02f"
onmouseover="this.style.backgroundColor='#6d8c24'"
onmouseout="this.style.backgroundColor='#8eb02f'"
x-on:click="addModal=true">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
</svg>
Nuevo usuario
</button>
</div>
</div>
<!-- Agregar el GIF de carga -->
<div x-show="loading" class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-50 justify-center items-center">
<img src="../img/loading.gif" alt="Cargando..." class="w-16 h-16" />
</div>
<div class="overflow-x-auto max-w-full">
<!-- Tabla de registros -->
<table class=" table-auto w-full">
<thead class="text-sm text-left py-4 border-b border-gray-300">
<tr class="text-left font-semibold border-collapse">
<th class="py-2 px-4 border-b w-52">Nombre</th>
<th class="py-2 px-4 border-b w-52">Usuario</th>
<th class="py-2 px-4 border-b">Estado</th>
<th class="py-2 px-4 border-b">Email</th>
<th class="py-2 px-4 border-b">Rol</th>
<th class="py-2 px-4 border-b">Verificado</th>
<th class="py-2 px-4 border-b w-32"></th>
</tr>
</thead>
<tbody class="text-gray-500 select-none text-sm ">
<template x-for="user in users" :key="user.ID">
<tr>
<td class="py-3 text-xs px-4 border-b" x-text="user.name"></td>
<td class="py-3 text-xs px-4 border-b" x-text="user.nombre_usuario"></td>
<td class="py-3 text-xs px-4 border-b">
<button class="w-9 h-5 rounded-full transition-colors duration-200"
:title="user.estado ? 'Activo' : 'Inactivo'"
:class="user.estado ? 'bg-green-500' : 'bg-gray-300'"
@click="toggleEstado(user.ID, user.estado)">
<div class="w-5 h-5 bg-white rounded-full shadow-gray-400 shadow transform ring-0 transition-transform duration-300"
:class="user.estado ? 'translate-x-full' : ''">
</div>
</button>
</td>
<td class="py-3 text-xs px-4 border-b" x-text="user.email"></td>
<td class="py-3 text-xs px-4 border-b" x-text="user.Role.name"></td>
<td class="py-3 text-xs px-4 border-b">
<template x-if="user.email_verified == true">
<div class="flex space-x-2">
<div class="w-2 h-2 rounded-full mr-1 align-middle my-auto bg-green-500"></div>
<span>Si</span>
</div>
<!-- Círculo verde -->
</template>
<!-- Botón Enviar credenciales -->
<button @click="enviarCredenciales(user.ID, user.email)" title="Enviar credenciales por email"
x-show="user.email">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="w-5 text-blue-500">
<path stroke-linecap="round" stroke-linejoin="round"
d="M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75" />
</svg>
</button>
</td>
<td class="py-3 text-xs px-4 border-b flex justify-between space-x-1">
<!-- Botón de Ver -->
<button @click="
viewModal = true;
Name = user.name;
NombreUsuario = user.nombre_usuario;
Estado = user.estado;
Email = user.email;
roleName = user.Role.name;
" title="Ver">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="w-5 text-[#8eb02f]">
<path stroke-linecap="round" stroke-linejoin="round"
d="M2.036 12.322a1.012 1.012 0 0 1 0-.639C3.423 7.51 7.36 4.5 12 4.5c4.638 0 8.573 3.007 9.963 7.178.07.207.07.431 0 .639C20.577 16.49 16.64 19.5 12 19.5c-4.638 0-8.573-3.007-9.963-7.178Z" />
<path stroke-linecap="round" stroke-linejoin="round"
d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
</svg>
</button>
<!-- Botón de Editar -->
<button @click="
editModal = true;
Id = user.ID;
Name = user.name;
NombreUsuario = user.nombre_usuario;
Estado = user.estado;
Email = user.email;
roleName = user.Role.ID;
" title="Editar">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="w-5">
<path stroke-linecap="round" stroke-linejoin="round"
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L10.582 16.07a4.5 4.5 0 0 1-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 0 1 1.13-1.897l8.932-8.931Zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0 1 15.75 21H5.25A2.25 2.25 0 0 1 3 18.75V8.25A2.25 2.25 0 0 1 5.25 6H10" />
</svg>
</button>
<!-- Botón de Eliminar -->
<button @click="showConfirmModal = true; deleteId = user.ID;" title="Eliminar">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="w-5 text-red-500">
<path stroke-linecap="round" stroke-linejoin="round"
d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0" />
</svg>
</button>
</td>
</tr>
</template>
<!-- Mensaje de Cargando -->
<tr x-show="isLoading">
<td colspan="6" class="py-2 px-4 border-b text-center">
<div class="text-center flex justify-center">
<svg class="animate-spin h-5 w-5 text-gray-500" xmlns="http://www.w3.org/2000/svg"
fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor"
stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z">
</path>
</svg>
Cargando registros...
</div>
</td>
</tr>
</tbody>
</table>
</div>
<div>
<!-- Los botones de paginación se generarán aquí -->
<div id="pagination" class="flex justify-left my-4 text-sm">
</div>
<!-- Mostrar conteo de registros -->
<div id="recordCountDiv" class="text-sm text-gray-700 ml-4">
</div>
</div>
</div>
<!-- Modal Ver -->
<div x-cloak x-show="viewModal" x-transition
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
<h2 class="text-xl font-bold mb-2">Ver registro</h2>
<p class="font-semibold" x-text="Name"></p> <!-- Muestra el nombre -->
<p class="mt-2" x-text="NombreUsuario"></p> <!-- Muestra el nombre de usuario -->
<p class="mt-2 flex items-center">
<!-- Punto de color basado en el estado -->
<span :class="Estado ? 'bg-green-500' : 'bg-gray-400'"
class="inline-block w-3 h-3 rounded-full mr-2"></span>
<!-- Texto del estado (puedes personalizarlo) -->
<span x-text="Estado ? 'Activo' : 'Inactivo'"></span>
</p>
<p class="mt-2" x-text="Email"></p> <!-- Muestra el correo -->
<p class="mt-2" x-text="roleName"></p> <!-- Muestra el nombre del rol -->
<button class="mt-4 bg-[#8eb02f] text-white px-4 py-2 rounded"
x-on:click="viewModal = false">Cerrar</button>
</div>
</div>
<!-- Modal Editar -->
<div x-cloak x-show="editModal" x-transition
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
<h2 class="text-xl font-bold mb-2">Editar registro</h2>
<form @submit.prevent="submitEdit">
<!-- Nombre -->
<label class="block mb-2" for="editName">Nombre</label>
<input type="text" id="editName" x-model="Name" placeholder="Nombre"
class="border border-gray-300 rounded w-full p-2" required>
<!-- Nombre de usuario -->
<label class="block mt-4 mb-2" for="editUsername">Nombre de usuario</label>
<input id="editUsername" x-model="NombreUsuario" placeholder="Nombre de usuario"
class="border border-gray-300 rounded w-full p-2" required>
<!-- Email -->
<label class="block mt-4 mb-2" for="editEmail">Email</label>
<input id="editEmail" x-model="Email" placeholder="Email"
class="border border-gray-300 rounded w-full p-2" required>
<!-- Cambiar contraseña -->
<div class="bg-[#8eb02f] text-white px-4 py-2 mt-2 rounded text-center cursor-pointer"
x-on:click="showPasswordModal = true;" title="Cambiar contraseña">Cambiar contraseña</div>
<!-- Rol -->
<label class="block mt-4 mb-2" for="editRole">Rol</label>
<select id="editRole" x-model="roleName" class="border border-gray-300 rounded w-full p-2" required>
<option value="" disabled selected>Selecciona un rol</option> <!-- Opción predeterminada -->
<template x-for="role in roles" :key="role.ID">
<option :value="role.ID" x-text="role.name"></option>
</template>
</select>
<div class="mt-4 flex justify-between">
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar Cambios</button>
<button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
x-on:click="closeModal">Cancelar</button>
</div>
</form>
</div>
</div>
<!-- Modal Añadir -->
<div x-cloak x-show="addModal" x-transition
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
<h2 class="text-xl font-bold mb-2">Agregar registro</h2>
<form @submit.prevent="submitAdd">
<label class="block mb-2" for="name">Nombre</label>
<input type="text" id="name" x-model="newName" placeholder="Nombre"
class="border border-gray-300 rounded w-full p-2" required>
<label class="block mt-4 mb-2" for="nombre_usuario">Nombre de usuario</label>
<input type="text" id="nombre_usuario" x-model="newNombreUsuario" placeholder="Nombre usuario"
class="border border-gray-300 rounded w-full p-2" required>
<label class="block mt-4 mb-2" for="editEmail">Email</label>
<input id="editEmail" x-model="newEmail" placeholder="Email" type="email"
class="border border-gray-300 rounded w-full p-2" required>
<label class="block mt-4 mb-2" for="editRole">Rol</label>
<select id="editRole" x-model="newRole" class="border border-gray-300 rounded w-full p-2" required>
<option value="" disabled selected>Selecciona un rol</option> <!-- Opción predeterminada -->
<template x-for="role in roles" :key="role.ID">
<option :value="role.ID" x-text="role.name"></option>
</template>
</select>
<div class="mt-4 flex justify-between">
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar </button>
<button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
x-on:click="closeModal">Cancelar</button>
</div>
</form>
</div>
</div>
<!-- Modal Confirmar Eliminación -->
<div x-cloak x-show="showConfirmModal" x-transition
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
<h2 class="text-xl font-bold mb-4">Confirmar Eliminación</h2>
<p>¿Estás seguro de que deseas eliminar este registro?</p>
<div class="mt-4 flex justify-end">
<button class="bg-red-500 text-white px-4 py-2 rounded mr-2" @click="deleteItem()">Eliminar</button>
<button @click="closeModal" class="bg-gray-600 text-white px-4 py-2 rounded">Cancelar</button>
</div>
</div>
</div>
<!-- Modal cambiar contraseña -->
<div x-cloak x-show="showPasswordModal" x-transition
class="fixed inset-0 bg-gray-800 bg-opacity-75 flex z-40 justify-center items-center text-sm">
<div class="bg-white p-6 rounded shadow-lg max-w-sm w-full overflow-y-auto max-h-full">
<form @submit.prevent="changePass">
<label class="block mb-2" for="password">Nueva contraseña</label>
<input type="text" id="password" x-model="password" placeholder="Ingrese una contraseña"
class="border border-gray-300 rounded w-full p-2" required>
<div class="mt-4 flex justify-between">
<button type="submit" class="bg-[#8eb02f] text-white px-4 py-2 rounded">Guardar </button>
<button type="button" class="bg-gray-600 text-white px-4 py-2 rounded"
x-on:click="closeModalPassword">Cancelar</button>
</div>
</form>
</div>
</div>
<!-- Alpine.js Script -->
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('modals', () => ({
addModal: false,
editModal: false,
viewModal: false,
showConfirmModal: false,
showPasswordModal: false,
newName: '',
newEmail: '',
newRole: '',
newNombreUsuario: '',
Name: '',
NombreUsuario: '',
Estado: '',
NewEstado: '',
Email: '',
roleName: '',
password: '',
userId: '',
Id: null,
deleteId: null,
users: [],
roles: [],
loading: false,
totalRecords: 0,
totalPages: 0,
isLoading: false,
init() {
this.loadRegister();
},
//CARGAR registros
searchQuery: '', // Agrega esta línea dentro del objeto Alpine
// Modifica la función loadRegister para incluir la búsqueda
loadRegister(page = 1) {
this.isLoading = true;
//this.loading = true;
const search = this.searchQuery ? `&search=${this.searchQuery}` : '';
fetch(`/app/loadusers?page=${page}${search}`)
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => {
this.totalRecords = data.total || 0;
this.users = data.Users || [];
this.roles = data.Roles || [];
this.totalPages = data.totalPages || 0;
this.createPagination(this.totalPages, page);
if (this.users.length > 0) {
const totalPages = Math.ceil(this.totalRecords / (data.limit || 10));
this.createPagination(totalPages, page);
}
})
.catch(error => console.error('Error cargando usuarios:', error))
.finally(() => {
this.isLoading = false; // Ocultar el GIF de carga
});
},
createPagination(totalPages, currentPage) {
const paginationContainer = document.getElementById('pagination');
paginationContainer.innerHTML = ''; // Limpiar la paginación actual
// Crear un contenedor para los botones de paginación
const paginationButtonsContainer = document.createElement('div');
paginationButtonsContainer.className = "md:flex mx-auto mb-2 md:justify-between items-center w-full"; // Alinear los botones
// Función para crear un botón
const createButton = (text, isDisabled, onClick, additionalClasses = '') => {
const button = document.createElement('button');
button.textContent = text;
button.disabled = isDisabled;
button.className = `px-4 py-2 text-black bg-gray-200 ${additionalClasses} ${isDisabled ? 'opacity-50 cursor-not-allowed' : 'hover:bg-gray-300'}`;
if (!isDisabled) {
button.onclick = onClick;
}
return button;
};
// Botones de paginación
const leftContainer = document.createElement('div');
leftContainer.className = "md:flex text-center mb-2"; // Contenedor para los botones de paginación a la izquierda
leftContainer.appendChild(createButton('Anterior', currentPage === 1, () => this.loadRegister(currentPage - 1), 'rounded-l-md'));
for (let i = 1; i <= totalPages; i++) {
const pageButton = createButton(i, false, () => this.loadRegister(i), `mx-1 ${i === currentPage ? 'bg-black text-gray-50' : 'bg-white text-black'} rounded-md`);
leftContainer.appendChild(pageButton);
}
leftContainer.appendChild(createButton('Siguiente', currentPage === totalPages, () => this.loadRegister(currentPage + 1), 'rounded-r-md'));
paginationButtonsContainer.appendChild(leftContainer);
// Agregar el conteo de registros a la derecha
const recordCountDiv = document.createElement('div');
const startRecord = (currentPage - 1) * 10 + 1; // Primer registro de la página actual
const endRecord = Math.min(currentPage * 10, this.totalRecords); // Último registro mostrado
recordCountDiv.className = "text-sm text-gray-700 text-center md:ml-auto"; // Sin margen para alineación a la izquierda
recordCountDiv.innerHTML = `Mostrando ${startRecord} a ${endRecord} de ${this.totalRecords} registros`;
paginationButtonsContainer.appendChild(recordCountDiv);
// Agregar los botones de paginación al contenedor principal
paginationContainer.appendChild(paginationButtonsContainer);
},
//CERRAR MODALES
closeModal() {
this.addModal = false;
this.editModal = false;
this.viewModal = false;
this.showConfirmModal = false;
},
//CERRAR MODAL PASS
closeModalPassword() {
this.showPasswordModal = false;
},
//CREAR
submitAdd() {
this.loading = true;
fetch('/app/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.newName,
nombre_usuario: this.newNombreUsuario,
email: this.newEmail,
role_id: parseInt(this.newRole),
estado: true,
tipo: 'sistema'
})
})
.then(response => response.json())
.then(() => {
this.newName = '';
this.newNombreUsuario = '';
this.newEmail = '';
this.newRole = '';
this.closeModal();
this.loadRegister();
})
.catch(error => console.error('Error:', error))
.finally(() => {
this.loading = false; // Ocultar el GIF de carga
});
},
//ACTUALIZAR
submitEdit() {
this.loading = true;
fetch(`/app/users/${this.Id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: this.Name, // Usar 'Name' en lugar de 'First_name'
nombre_usuario: this.NombreUsuario, // Usar 'Nombre_usuario' en lugar de 'Last_name'
email: this.Email, // Usar 'Email'
role_id: parseInt(this.roleName) // Usar 'roleName'
})
})
.then(response => response.json())
.then(() => {
// Limpiar campos después de la actualización
this.Name = '';
this.NombreUsuario = '';
this.Email = '';
this.roleName = '';
this.closeModal();
this.loadRegister();
})
.catch(error => console.error('Error:', error))
.finally(() => {
this.loading = false; // Ocultar el GIF de carga
});
},
//ACTUALIZAR PASS
changePass() {
this.loading = true;
fetch(`/app/password/${this.Id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
password: this.password,
})
})
.then(response => response.json())
.then(() => {
this.password = '';
this.closeModalPassword();
})
.catch(error => console.error('Error:', error))
.finally(() => {
this.loading = false; // Ocultar el GIF de carga
});
},
//TOGGLE ESTADO
toggleEstado($id, $estado) {
this.Id = $id;
this.NewEstado = $estado;
this.loading = true;
if (this.NewEstado) {
this.NewEstado = false;
} else {
this.NewEstado = true;
}
console.log(this.NewEstado);
fetch(`/app/users/${this.Id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
estado: this.NewEstado
})
})
.then(response => response.json())
.then(() => {
this.loadRegister();
})
.catch(error => console.error('Error:', error))
.finally(() => {
this.loading = false; // Ocultar el GIF de carga
});
},
//ELIMINAR
deleteItem() {
this.loading = true;
fetch(`/app/users/${this.deleteId}`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' }
})
.then(() => {
this.closeModal();
this.loadRegister();
})
.catch(error => console.error('Error:', error))
.finally(() => {
this.loading = false; // Ocultar el GIF de carga
});
},
async enviarCredenciales($id, $email) {
if (!confirm(`¿Enviar credenciales de acceso a ${$email}?`)) return;
this.loading = true;
try {
const r = await fetch(`/app/users/${$id}/credenciales`, { method: 'POST' });
const data = await r.json();
alert(data.message || 'Credenciales enviadas');
} catch (e) {
alert('Error al enviar credenciales');
} finally {
this.loading = false;
}
}
}));
});
</script>
</div>