848 lines
39 KiB
PHP
848 lines
39 KiB
PHP
<?php
|
|
|
|
session_start();
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: index.php');
|
|
exit();
|
|
}
|
|
|
|
?>
|
|
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.css">
|
|
<link rel="shortcut icon" href="assets/img/favicon.png">
|
|
|
|
<!-- DataTables Buttons CSS -->
|
|
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.0.1/css/buttons.dataTables.min.css">
|
|
|
|
<style>
|
|
/* Estilo del switch */
|
|
.switch {
|
|
position: relative;
|
|
display: inline-block;
|
|
width: 60px;
|
|
height: 34px;
|
|
}
|
|
|
|
/* Ocultar el checkbox original */
|
|
.switch input {
|
|
opacity: 0;
|
|
width: 0;
|
|
height: 0;
|
|
}
|
|
|
|
/* Estilo del slider del switch */
|
|
.slider {
|
|
position: absolute;
|
|
cursor: pointer;
|
|
top: 0;
|
|
left: 0;
|
|
right: 0;
|
|
bottom: 0;
|
|
background-color: #ccc;
|
|
transition: .4s;
|
|
border-radius: 34px;
|
|
}
|
|
|
|
/* Estilo del indicador del switch (punto que se desplaza) */
|
|
.slider:before {
|
|
position: absolute;
|
|
content: "";
|
|
height: 26px;
|
|
width: 26px;
|
|
left: 4px;
|
|
bottom: 4px;
|
|
background-color: white;
|
|
transition: .4s;
|
|
border-radius: 50%;
|
|
}
|
|
|
|
/* Cambiar el estilo cuando el switch está encendido */
|
|
input:checked+.slider {
|
|
background-color: #2196F3;
|
|
}
|
|
|
|
input:focus+.slider {
|
|
box-shadow: 0 0 1px #2196F3;
|
|
}
|
|
|
|
input:checked+.slider:before {
|
|
transform: translateX(26px);
|
|
}
|
|
</style>
|
|
</head>
|
|
|
|
<body>
|
|
<div class="container">
|
|
<input type="text" id="dato" hidden>
|
|
<br><br><br>
|
|
<h2>Usuarios</h2>
|
|
<button id="exportButton" class="btn btn-success" style="position: relative;top: 0px;left: 205px;">Excel</button>
|
|
<button id="exportButtonPDF" class="btn btn-danger" style="position: relative;top: 0px;left: 205px;" onclick="exportToPDF()">PDF</button>
|
|
<button id="AgreUser" class="btn btn-primary" style="position: relative;top: 0px;left: 205px;">Agregar</button>
|
|
<div class="table-responsive">
|
|
<table class="table" id="usersTable">
|
|
<thead>
|
|
<tr>
|
|
<th scope="col">Correo</th>
|
|
<th scope="col">Nombre</th>
|
|
<th scope="col">CeCo</th>
|
|
<th scope="col">Unidad de negocio</th>
|
|
<th scope="col">CENTRO</th>
|
|
<th scope="col">Estatus</th>
|
|
<th scope="col">Acciones</th>
|
|
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- //MODIFICAR MODAL-->
|
|
<div class="modal fade" role="dialog" tabindex="-1" id="myModal">
|
|
<div class="modal-dialog modal-lg" role="document">
|
|
<div class="modal-content">
|
|
<!-- Contenido de la ventana emergente -->
|
|
<div class="modal-header">
|
|
<h5 class="modal-title">Modificar Usuario</h5>
|
|
<button type="button" class="close" onclick="cerrarModal2('myModal')" aria-label="Close">
|
|
<span aria-hidden="true">×</span>
|
|
</button>
|
|
<!-- <button type="button" class="close" data-dismiss="modal">
|
|
<span aria-hidden="true">x</span>
|
|
</button> -->
|
|
</div>
|
|
<div class="modal-body" id="modalBody">
|
|
<!-- Contenido dinámico se agregará aquí -->
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="cerrarModal2('myModal')">Cerrar</button>
|
|
<button type="button" class="btn btn-primary" id="guardarCambiosBtn">Guardar
|
|
Cambios</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- Modal Crear Usuario -->
|
|
<div class="modal" tabindex="-1" role="dialog" id="miModal2">
|
|
<div class="modal-dialog" role="document">
|
|
<div class="modal-content">
|
|
<!-- Contenido del modal -->
|
|
<div class="modal-header">
|
|
<h5 class="modal-title">Crear Usuario</h5>
|
|
<button type="button" class="close" data-dismiss="modal" aria-label="Cerrar" onclick="cerrarModal2('miModal2')">
|
|
<span aria-hidden="true">×</span>
|
|
</button>
|
|
</div>
|
|
<div class="modal-body">
|
|
<!-- Aquí puedes colocar campos para mostrar o modificar datos -->
|
|
<label for="correoInput">Correo:</label>
|
|
<input type="text" id="correoInput" class="form-control" required>
|
|
<label for="nombreInput">Nombre:</label>
|
|
<input type="text" id="nombreInput" class="form-control" required>
|
|
<label for="passwordInput">Contraseña:</label>
|
|
<input type="password" id="passwordInput" class="form-control" required>
|
|
<label for="centroInput">Centro de costos:</label>
|
|
<input type="text" id="centroInput" class="form-control" required>
|
|
<label for="unidadInput">Unidad de negocio:</label>
|
|
<input type="text" id="unidadInput" class="form-control" required>
|
|
<label for="centroInput">Centro:</label>
|
|
<input type="text" id="centro" class="form-control" required>
|
|
<label for="fotoInput">Foto:</label>
|
|
<input type="file" id="fotoInput" class="form-control custom-file-input" accept="image/*">
|
|
<input type="text" id="img" style="display: none;">
|
|
<label for="rolesInput">Roles:</label> <br>
|
|
<div class="form-check form-switch">
|
|
<input class="form-check-input" type="checkbox" id="creacionSwitch">
|
|
<label class="form-check-label" for="creacionSwitch">Creación / Cancelación</label>
|
|
</div>
|
|
<div class="form-check form-switch">
|
|
<input class="form-check-input" type="checkbox" id="complementoPagoSwitch">
|
|
<label class="form-check-label" for="complementoPagoSwitch">Complemento de pago</label>
|
|
</div>
|
|
<div class="form-check form-switch">
|
|
<input class="form-check-input" type="checkbox" id="complementosSwitch">
|
|
<label class="form-check-label" for="complementosSwitch">Complementos</label>
|
|
</div>
|
|
<div class="form-check form-switch">
|
|
<input class="form-check-input" type="checkbox" id="visualizacionSwitch">
|
|
<label class="form-check-label" for="visualizacionSwitch">Visualización</label>
|
|
</div>
|
|
<div class="form-check form-switch">
|
|
<input class="form-check-input" type="checkbox" id="modificacionUsuariosSwitch">
|
|
<label class="form-check-label" for="modificacionUsuariosSwitch">Modificación de Usuarios</label>
|
|
</div>
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="cerrarModal2('miModal2')">Cerrar</button>
|
|
<button type="button" class="btn btn-primary" onclick="guardarDatos()">Guardar</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- Modal de Confirmación de Eliminación -->
|
|
<div class="modal fade" id="confirmarEliminacionModal" tabindex="-1" role="dialog" aria-labelledby="confirmarEliminacionModalLabel" aria-hidden="true">
|
|
<div class="modal-dialog" role="document">
|
|
<div class="modal-content">
|
|
<div class="modal-header">
|
|
<h5 class="modal-title" id="confirmarEliminacionModalLabel">Confirmar Eliminación</h5>
|
|
<button type="button" class="close cancelarEliminacionBtn" data-dismiss="modal" aria-label="Close">
|
|
<span aria-hidden="true">×</span>
|
|
</button>
|
|
</div>
|
|
<div class="modal-body">
|
|
¿Estás seguro de que deseas eliminar este usuario?
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="button" class="btn btn-secondary cancelarEliminacionBtn" data-dismiss="modal">Cancelar</button>
|
|
<button type="button" class="btn btn-danger" id="confirmarEliminacionBtn">Eliminar</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<!-- Botón para abrir el modal -->
|
|
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modalUsuario">
|
|
Ver Detalles
|
|
</button>
|
|
|
|
<!-- Modal vi-->
|
|
<div class="modal fade" id="modalUsuario" tabindex="-1" role="dialog" aria-labelledby="modalUsuarioLabel" aria-hidden="true">
|
|
<div class="modal-dialog" role="document">
|
|
<div class="modal-content">
|
|
<div class="modal-header">
|
|
<h5 class="modal-title" id="modalUsuarioLabel">Detalles del Usuario</h5>
|
|
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="cerrarModal2('modalUsuario')">
|
|
<span aria-hidden="true">×</span>
|
|
</button>
|
|
</div>
|
|
<div class="modal-body">
|
|
<!-- Aquí mostrarás los detalles del usuario -->
|
|
<p><strong>Id:</strong> <span id="modalId"></span></p>
|
|
<p><strong>Correo:</strong> <span id="modalCorreo"></span></p>
|
|
<p><strong>Nombre:</strong> <span id="modalNombre"></span></p>
|
|
<p><strong>Fecha de creación:</strong> <span id="modalFechaCreacion"></span></p>
|
|
<p><strong>Ceco:</strong> <span id="modalCeco"></span></p>
|
|
<p><strong>Unidad de negocio:</strong> <span id="modalUnidadNegocio"></span></p>
|
|
<p><strong>Centro:</strong> <span id="modalCentro"></span></p>
|
|
<p><strong>Foto:</strong> <img id="modalFoto" class="img-fluid"></p>
|
|
<p><strong>Rol:</strong> <span id="modalRol"></span></p>
|
|
<!-- Añade más elementos según necesites -->
|
|
</div>
|
|
<div class="modal-footer">
|
|
<button type="button" class="btn btn-secondary" data-dismiss="modal" onclick="cerrarModal2('modalUsuario')">Cerrar</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
|
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
|
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
|
|
<script src="https://cdn.datatables.net/buttons/2.0.1/js/dataTables.buttons.min.js"></script>
|
|
<script src="https://cdn.datatables.net/buttons/2.0.1/js/buttons.html5.min.js"></script>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
|
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.5/xlsx.full.min.js"></script>
|
|
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
|
|
|
<script>
|
|
var foto = ""
|
|
|
|
function consultarCorreo(correo_bus) {
|
|
return new Promise(function(resolve, reject) {
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: './ManipulacionUser.php',
|
|
data: {
|
|
operacion: "consultaPorCorreo",
|
|
Correo: correo_bus
|
|
},
|
|
success: function(response) {
|
|
var jsonResponse = JSON.parse(response);
|
|
var respuesta = [];
|
|
|
|
if (jsonResponse && jsonResponse.Usuarios && jsonResponse.Usuarios.length > 0) {
|
|
var user = jsonResponse.Usuarios[0];
|
|
respuesta.push(user.Id);
|
|
respuesta.push(user.Correo);
|
|
respuesta.push(user.Nombre);
|
|
respuesta.push(user.Ceco);
|
|
respuesta.push(user.Unidad);
|
|
respuesta.push(user.Centro);
|
|
respuesta.push(user.Estatus);
|
|
respuesta.push(user.Rol);
|
|
respuesta.push(user.Fecha);
|
|
respuesta.push(user.Foto);
|
|
resolve(respuesta);
|
|
} else {
|
|
console.error('No se encontraron usuarios con el correo proporcionado');
|
|
resolve(null); // Devolver null cuando el correo no existe
|
|
}
|
|
},
|
|
error: function(error) {
|
|
console.error('Error en la solicitud:', error);
|
|
reject(error);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
|
|
|
|
$(document).ready(function() {
|
|
var table = $('#usersTable').DataTable({
|
|
lengthMenu: [10, 25, 50, 100],
|
|
pageLength: 10,
|
|
searching: true,
|
|
paging: true,
|
|
ordering: true,
|
|
info: true,
|
|
responsive: true,
|
|
dom: 'Blfrtip',
|
|
buttons: [{
|
|
extend: 'pdf',
|
|
className: 'btn btn-danger'
|
|
}]
|
|
});
|
|
|
|
|
|
// Agrega control de selección de longitud
|
|
table.buttons().container().appendTo('#usersTable_wrapper .col-md-6:eq(0)');
|
|
|
|
var facturasEnviar = [];
|
|
var responsesArray = [];
|
|
var estado = 0;
|
|
|
|
// Obtener el índice de inicio de la página actual
|
|
var currentPageStartIndex = table.page.info().start;
|
|
|
|
|
|
$.ajax({
|
|
url: './ManipulacionUser.php',
|
|
type: 'POST',
|
|
data: {
|
|
operacion: "consulta"
|
|
},
|
|
dataType: 'json',
|
|
success: function(response) {
|
|
var users = response.Usuarios;
|
|
// Limpiar la tabla antes de agregar nuevas filas
|
|
table.clear().draw();
|
|
|
|
|
|
users.forEach(function(user) {
|
|
// Filtrar propiedades no deseadas (password y created_at)
|
|
|
|
var filteredUser = {
|
|
Correo: user.Correo,
|
|
Nombre: user.Nombre,
|
|
CeCo: user.Ceco,
|
|
Unidad_de_negocio: user.Unidad,
|
|
Centro: user.Centro,
|
|
Estatus: user.Estatus,
|
|
Rol: user.Rol
|
|
// Agrega las otras propiedades según sea necesarioS
|
|
};
|
|
//console.log(filteredUser.Correo);
|
|
// paswords.push(filteredUser.Contrasena);
|
|
// Agregar las columnas según la estructura filtrada
|
|
table.row.add([
|
|
filteredUser.Correo,
|
|
filteredUser.Nombre,
|
|
filteredUser.CeCo,
|
|
filteredUser.Unidad_de_negocio,
|
|
filteredUser.Centro,
|
|
'<label class="switch">' +
|
|
'<input class="form-check-input custom-toggle" type="checkbox" ' + (filteredUser.Estatus == 1 ? 'checked' : '') + '>' +
|
|
'<span class="slider"></span>' +
|
|
'</label>',
|
|
'<div><img src="./images/editar.png" alt="Editar" class="img-fluid ImgModificar" data-id="' + filteredUser.Correo + '">' +
|
|
'<img src="./images/visibilidad.png" alt="Visualizar" class="img-fluid" data-id="' + filteredUser.Correo + '" onclick="mostrarDetallesUsuario(\'' + filteredUser.Correo + '\')">' +
|
|
'<img src="./images/eliminar.png" alt="Eliminar" class="img-fluid" data-id="' + filteredUser.Correo + '" onclick="EliminarUser(\'' + filteredUser.Correo + '\')">' +
|
|
'</div>'
|
|
// Agrega las otras columnas según sea necesario
|
|
//calcular la antiguedad diferencia de dias
|
|
|
|
]).draw(false);
|
|
});
|
|
},
|
|
error: function(error) {
|
|
console.error('Error en la solicitud:', error);
|
|
}
|
|
});
|
|
//Actualizar campo ESTATUS
|
|
|
|
$('#usersTable').on('change', '.custom-toggle', function() {
|
|
var rowData = table.row($(this).closest('tr')).data();
|
|
var id = rowData[0]; // Asegúrate de tener una propiedad 'id' en tu objeto de datos
|
|
|
|
// Obtener el nuevo valor del checkbox
|
|
var nuevoEstatus = $(this).prop('checked') ? 1 : 0;
|
|
|
|
// Realizar la llamada AJAX para actualizar el estatus en la base de datos
|
|
$.ajax({
|
|
url: './ManipulacionUser.php', // Ajusta la URL según tu estructura
|
|
type: 'POST',
|
|
data: {
|
|
operacion: "actualizarestatus",
|
|
Correo: id,
|
|
Estatus: nuevoEstatus
|
|
},
|
|
success: function(response) {
|
|
console.log(response);
|
|
// Puedes realizar acciones adicionales después de la actualización si es necesario
|
|
},
|
|
error: function(error) {
|
|
console.error('Error en la llamada AJAX', error);
|
|
}
|
|
});
|
|
});
|
|
$('#usersTable').off('click').on('click', '.ImgModificar', function() {
|
|
var dataMod = table.row($(this).parents('tr')).data();
|
|
// Excluir las dos últimas columnas (botones)
|
|
var excludedColumns = 2; // Cambia esto al número de columnas que deseas excluir
|
|
var rowData = dataMod.slice(0, dataMod.length - excludedColumns);
|
|
|
|
// Implementar lógica para modificar con los datos en 'data'
|
|
abrirModalModificar(rowData);
|
|
console.log("Abre modal User", dataMod);
|
|
});
|
|
});
|
|
|
|
function abrirModalModificar(rowData) {
|
|
// Limpiar el contenido anterior del modal
|
|
$('#modalBody').empty();
|
|
var inputHtml;
|
|
var correoinicial = rowData[0];
|
|
|
|
// Generar dinámicamente los inputs basándonos en los datos de la fila
|
|
Object.keys(rowData).forEach(function(key) {
|
|
if (key !== 'created_at' && key !== 'estatus' && key !== 'password') {
|
|
//console.log(rowData[key])
|
|
if (key === '0') {
|
|
inputHtml = '<div class="form-group">' +
|
|
'<label for="' + key + '">Correo:</label>' +
|
|
'<input type="text" class="form-control" id="' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>';
|
|
} else if (key === '1') {
|
|
inputHtml = '<div class="form-group">' +
|
|
'<label for="' + key + '">Nombre:</label>' +
|
|
'<input type="text" class="form-control" id="' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>';
|
|
} else if (key === '2') {
|
|
inputHtml = '<div class="form-group">' +
|
|
'<label for="' + key + '">CeCo:</label>' +
|
|
'<input type="text" class="form-control" id="' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>';
|
|
} else if (key === '3') {
|
|
inputHtml = '<div class="form-group">' +
|
|
'<label for="' + key + '">Unidad de negocio:</label>' +
|
|
'<input type="text" class="form-control" id="' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>';
|
|
} else if (key === '4') {
|
|
inputHtml = '<div class="form-group">' +
|
|
'<label for="' + key + '">Centro:</label>' +
|
|
'<input type="text" class="form-control" id="' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>' +
|
|
'<div class="form-group">' +
|
|
'<label for="' + key + '">Password:</label>' +
|
|
'<input type="password" class="form-control" id="contra' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>';
|
|
} else {
|
|
inputHtml = '<div class="form-group">' +
|
|
'<label for="' + key + '">' + key + '</label>' +
|
|
'<input type="text" class="form-control" id="' + key + '" value="' + rowData[key] + '">' +
|
|
'</div>'
|
|
}
|
|
$('#modalBody').append(inputHtml);
|
|
}
|
|
});
|
|
inputHtml = '<label for="fotoInput">Foto:</label>' +
|
|
'<input type="file" id="fotoInput1" class="form-control custom-file-input" accept="image/*">' +
|
|
'<input type="text" id="img" hidden>' +
|
|
'<label for="rolesInput">Roles:</label> <br>' +
|
|
'<div class="form-check form-switch">' +
|
|
'<input class="form-check-input" type="checkbox" id="creacionSwitc">' +
|
|
'<label class="form-check-label" for="creacionSwitc">Creación / Cancelación</label>' +
|
|
'</div>' +
|
|
'<div class="form-check form-switch">' +
|
|
'<input class="form-check-input" type="checkbox" id="complementoPagoSwitc">' +
|
|
'<label class="form-check-label" for="complementoPagoSwitch">Complemento de pago</label> </div>' +
|
|
'<div class="form-check form-switch">' +
|
|
'<input class="form-check-input" type="checkbox" id="complementosSwitc">' +
|
|
'<label class="form-check-label" for="complementosSwitch">Complementos</label>' +
|
|
'</div>' +
|
|
'<div class="form-check form-switch">' +
|
|
'<input class="form-check-input" type="checkbox" id="visualizacionSwitc">' +
|
|
'<label class="form-check-label" for="visualizacionSwitch">Visualización</label> </div>' +
|
|
'<div class="form-check form-switch">' +
|
|
'<input class="form-check-input" type="checkbox" id="modificacionUsuariosSwitc">' +
|
|
'<label class="form-check-label" for="modificacionUsuariosSwitch">Modificación de Usuarios</label></div>'
|
|
$('#modalBody').append(inputHtml);
|
|
// Luego, al hacer clic en el botón de guardar en el modal, enviar la solicitud AJAX
|
|
$('#guardarCambiosBtn').off('click').on('click', async function() {
|
|
var newData = {};
|
|
// Obtener los nuevos valores desde los inputs del modal
|
|
Object.keys(rowData).forEach(function(key) {
|
|
if (key !== 'password' && key !== 'created_at') {
|
|
newData[key] = $('#' + key).val();
|
|
console.log("datos U " + newData[key]);
|
|
}
|
|
|
|
});
|
|
newData[5] = $('#contra4').val();
|
|
// agregar metodo
|
|
var creacionSwitch = $('#creacionSwitc').prop('checked') ? 1 : 0;
|
|
var complementoPagoSwitch = $('#complementoPagoSwitc').prop('checked') ? 1 : 0;
|
|
var complementosSwitch = $('#complementosSwitc').prop('checked') ? 1 : 0;
|
|
var visualizacionSwitch = $('#visualizacionSwitc').prop('checked') ? 1 : 0;
|
|
var modificacionUsuariosSwitch = $('#modificacionUsuariosSwitc').prop('checked') ? 1 : 0;
|
|
var rol = `${creacionSwitch},${complementoPagoSwitch},${complementosSwitch},${visualizacionSwitch},${modificacionUsuariosSwitch}`;
|
|
var fileInput = document.getElementById('fotoInput1'); //ELEMENTO FORMULARIO SELECTOR DE ARCHIVOS
|
|
var file = fileInput.files[0];
|
|
//validacion
|
|
if (newData[1] == "" || newData[2] == "" || newData[5] == "" || newData[3] == "" || newData[4] == "" || foto == "" || rol == "" || newData[0] == "") {
|
|
// Swal.fire('Campos incompletos.');
|
|
// return;
|
|
}
|
|
// const existeCorreo = await verificarCorreoExistente(correoinicial);
|
|
// if (existeCorreo) {
|
|
// Swal.fire('Correo existente; intente con otro.');
|
|
// return;
|
|
// }
|
|
// Uso de la función con una devolución de llamada
|
|
cargafoto(file, function(base64Data) {
|
|
//console.log(base64Data);
|
|
foto = base64Data
|
|
// Puedes realizar acciones adicionales con el valor base64 aquí
|
|
var data = {
|
|
operacion: 'actualizacion',
|
|
Correo: correoinicial,
|
|
Nombre: newData[1],
|
|
Ceco: newData[2],
|
|
Contrasena: newData[5],
|
|
Unidad_de_negocio: newData[3],
|
|
Centro: newData[4],
|
|
Foto: foto,
|
|
Rol: rol,
|
|
Correoprov: newData[0]
|
|
};
|
|
|
|
|
|
|
|
|
|
// Enviar la solicitud AJAX para la actualización
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: './ManipulacionUser.php', // Reemplazar con la ruta correcta a tu nuevo archivo PHP
|
|
data: data,
|
|
success: function(response) {
|
|
|
|
console.log(response);
|
|
// inicializarDataTable();
|
|
$('#myModal').modal('hide');
|
|
Swal.fire('Cambios registrados')
|
|
recarga();
|
|
},
|
|
error: function(error) {
|
|
console.error('Error en la llamada AJAX', error);
|
|
|
|
}
|
|
});
|
|
});
|
|
});
|
|
$('#myModal').modal('show');
|
|
}
|
|
|
|
function abrirModalagregar() {
|
|
$('#miModal2').modal('show');
|
|
}
|
|
|
|
function cerrarModal2(modal) {
|
|
$('#' + modal).modal('toggle');
|
|
}
|
|
|
|
$('#AgreUser').click(abrirModalagregar);
|
|
async function guardarDatos() {
|
|
$('#img').val('0');
|
|
// Obtener los valores de los campos del modal
|
|
var correo = $('#correoInput').val();
|
|
var nombre = $('#nombreInput').val();
|
|
var password = $('#passwordInput').val();
|
|
var unidadNegocio = $('#unidadInput').val();
|
|
var centroCostos = $('#centroInput').val();
|
|
var centro = $('#centro').val();
|
|
// Verificar si el archivo de la foto está presente
|
|
// Obtener el estado de los interruptores
|
|
var creacionSwitch = $('#creacionSwitch').prop('checked') ? 1 : 0;
|
|
var complementoPagoSwitch = $('#complementoPagoSwitch').prop('checked') ? 1 : 0;
|
|
var complementosSwitch = $('#complementosSwitch').prop('checked') ? 1 : 0;
|
|
var visualizacionSwitch = $('#visualizacionSwitch').prop('checked') ? 1 : 0;
|
|
var modificacionUsuariosSwitch = $('#modificacionUsuariosSwitch').prop('checked') ? 1 : 0;
|
|
var rol = `${creacionSwitch},${complementoPagoSwitch},${complementosSwitch},${visualizacionSwitch},${modificacionUsuariosSwitch}`;
|
|
if (correo == "" || nombre == "" || password == "" || unidadNegocio == "" || centroCostos == "" || centro == "") {
|
|
Swal.fire('Campos incompletos.');
|
|
return;
|
|
}
|
|
const existeCorreo = await verificarCorreoExistente(correo);
|
|
if (existeCorreo) {
|
|
Swal.fire('Correo existente; intente con otro.');
|
|
return;
|
|
}
|
|
// Enviar la solicitud AJAX para la creación
|
|
var fileInput = document.getElementById('fotoInput'); //ELEMENTO FORMULARIO SELECTOR DE ARCHIVOS
|
|
var file = fileInput.files[0];
|
|
// Uso de la función con una devolución de llamada
|
|
cargafoto(file, function(base64Data) {
|
|
//console.log(base64Data);
|
|
foto = base64Data
|
|
// Puedes realizar acciones adicionales con el valor base64 aquí
|
|
//console.log(foto)
|
|
var data = {
|
|
operacion: 'insercion',
|
|
Correo: correo,
|
|
Nombre: nombre,
|
|
Ceco: centroCostos,
|
|
Contrasena: password,
|
|
Unidad_de_negocio: unidadNegocio,
|
|
Centro: centro,
|
|
Estatus: 1,
|
|
Foto: foto,
|
|
Rol: rol
|
|
};
|
|
console.log(data.Foto)
|
|
//console.log(correo, " :correo ", nombre, " :name ", centroCostos, " :centroC ", password, " :contra ",
|
|
// unidadNegocio, " :unneg ", centro, " :centro - rol:", rol, " foto paaaa : ", foto);
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: './ManipulacionUser.php', // Reemplazar con la ruta correcta a tu nuevo archivo PHP
|
|
data: data,
|
|
success: function(response) {
|
|
console.log(response);
|
|
// inicializarDataTable();
|
|
$('#miModal2').modal('hide');
|
|
Swal.fire('Usuario registrado')
|
|
recarga();
|
|
},
|
|
error: function(error) {
|
|
console.error('Error en la llamada AJAX', error);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
function EliminarUser(correo) {
|
|
console.log(correo)
|
|
// Mostrar el modal de confirmación
|
|
$('#confirmarEliminacionModal').modal('show');
|
|
|
|
// Configurar la acción del botón "Eliminar" dentro del modal
|
|
$('#confirmarEliminacionBtn').on('click', function() {
|
|
// Aquí puedes realizar la lógica de eliminación, por ejemplo, haciendo una llamada AJAX
|
|
console.log("ya se elimino paaaa");
|
|
var data = {
|
|
operacion: 'eliminacion',
|
|
Correo: correo,
|
|
};
|
|
$.ajax({
|
|
type: 'POST',
|
|
url: './ManipulacionUser.php', // Reemplazar con la ruta correcta a tu nuevo archivo PHP
|
|
data: data,
|
|
success: function(response) {
|
|
|
|
console.log(response);
|
|
// inicializarDataTable();
|
|
$('#myModal').modal('hide');
|
|
Swal.fire('Usuario Eliminado')
|
|
recarga();
|
|
},
|
|
error: function(error) {
|
|
console.error('Error en la llamada AJAX', error);
|
|
}
|
|
});
|
|
// Después de realizar la eliminación, cierra el modal
|
|
$('#confirmarEliminacionModal').modal('hide');
|
|
});
|
|
|
|
$('.cancelarEliminacionBtn').on('click', function() {
|
|
$('#confirmarEliminacionModal').modal('hide');
|
|
});
|
|
}
|
|
|
|
function mostrarDetallesUsuario(correo) {
|
|
consultarCorreo(correo)
|
|
.then(function(respuesta) {
|
|
var id = respuesta[0];
|
|
var correo = respuesta[1];
|
|
var nombre = respuesta[2];
|
|
var ceco = respuesta[3];
|
|
var unidad = respuesta[4];
|
|
var centro = respuesta[5];
|
|
var estatus = respuesta[6];
|
|
var rol = respuesta[7];
|
|
var fecha = respuesta[8];
|
|
var foto = respuesta[9];
|
|
|
|
// Actualizar el contenido del modal
|
|
$('#modalId').text(id);
|
|
$('#modalCorreo').text(correo);
|
|
$('#modalNombre').text(nombre);
|
|
$('#modalFechaCreacion').text(fecha);
|
|
$('#modalCeco').text(ceco);
|
|
$('#modalUnidadNegocio').text(unidad);
|
|
$('#modalCentro').text(centro);
|
|
$('#modalFoto').attr('src', foto); // Asignar la fuente de la imagen
|
|
const rolesAsignados = obtenerRoles(rol);
|
|
deterroles(rolesAsignados, 'modalRol');
|
|
//console.log(foto)
|
|
// Actualiza los demás campos según sea necesario
|
|
// Abrir el modal
|
|
$('#modalUsuario').modal('show');
|
|
|
|
})
|
|
.catch(function(error) {
|
|
console.error('Error:', error);
|
|
});
|
|
}
|
|
|
|
function obtenerRoles(cadenaRoles) {
|
|
// Separar la cadena en roles individuales
|
|
const rolesArray = cadenaRoles.split(',');
|
|
|
|
// Definir los roles disponibles
|
|
const rolesDisponibles = [
|
|
"Creación / Cancelación",
|
|
"Complemento de pago",
|
|
"Complementos",
|
|
"Visualización",
|
|
"Modificación de Usuarios"
|
|
// Agrega más roles según sea necesario
|
|
];
|
|
|
|
// Crear un array que contenga los roles correspondientes
|
|
const rolesAsignados = rolesArray.reduce((result, valor, index) => {
|
|
if (valor === '1') {
|
|
result.push(rolesDisponibles[index]);
|
|
}
|
|
return result;
|
|
}, []);
|
|
console.log(rolesAsignados)
|
|
// Devolver los roles asignados como un array o cadena según tu preferencia
|
|
return rolesAsignados;
|
|
}
|
|
|
|
function cargafoto(file, callback) {
|
|
var base64String = "";
|
|
|
|
if (file) {
|
|
var maxSize = 1024 * 1024;
|
|
if (file.size > maxSize) {
|
|
Swal.fire('La foto excede el límite de peso');
|
|
return;
|
|
}
|
|
|
|
// Leer el archivo como base64
|
|
var reader = new FileReader();
|
|
reader.onload = function(e) {
|
|
base64String = e.target.result;
|
|
// Llamada a la devolución de llamada con el valor base64
|
|
callback(base64String);
|
|
};
|
|
reader.readAsDataURL(file);
|
|
} else {
|
|
Swal.fire('Selecciona una imagen');
|
|
return;
|
|
}
|
|
}
|
|
|
|
function deterroles(roles, id) {
|
|
// Obtener el elemento span por su id
|
|
const spanRol = document.getElementById(id);
|
|
|
|
// Crear una lista desordenada (<ul>) para mostrar los roles
|
|
const listaRoles = document.createElement('ul');
|
|
|
|
// Iterar sobre los roles y agregar cada uno como un elemento de lista (<li>)
|
|
roles.forEach(function(rol) {
|
|
const listItem = document.createElement('li');
|
|
listItem.textContent = rol;
|
|
listaRoles.appendChild(listItem);
|
|
});
|
|
|
|
// Limpiar el contenido existente en el span
|
|
spanRol.innerHTML = '';
|
|
|
|
// Agregar la lista de roles al span
|
|
spanRol.appendChild(listaRoles);
|
|
}
|
|
|
|
function recarga() {
|
|
setTimeout(function() {
|
|
location.reload();
|
|
}, 4000);
|
|
}
|
|
/*
|
|
function exportToPDF() {
|
|
var table = $('#usersTable').DataTable();
|
|
|
|
// Configuración específica para PDF
|
|
var pdfConfig = {
|
|
orientation: 'landscape', // 'portrait' para orientación vertical
|
|
pageSize: 'A4', // Puedes ajustar el tamaño del papel según tus necesidades
|
|
};
|
|
|
|
// Utilizar jsPDF para crear un nuevo documento PDF
|
|
var pdfDoc = new jsPDF(pdfConfig);
|
|
|
|
// Obtener el encabezado de la tabla
|
|
var header = [];
|
|
table.columns().every(function() {
|
|
header.push(this.header().textContent);
|
|
});
|
|
|
|
// Eliminar las dos últimas columnas del encabezado
|
|
header.splice(-2, 2);
|
|
|
|
// Obtener los datos de la tabla
|
|
var data = table.rows().data().toArray();
|
|
|
|
// Crear la tabla en el documento PDF
|
|
pdfDoc.autoTable({
|
|
head: [header], // Encabezado de la tabla
|
|
body: data, // Cuerpo de la tabla
|
|
startY: 10, // Posición inicial en la página
|
|
theme: 'striped', // Tema de la tabla (puedes ajustarlo según tus preferencias)
|
|
});
|
|
|
|
// Guardar el documento PDF
|
|
pdfDoc.save('Usuarios.pdf');
|
|
}*/
|
|
async function verificarCorreoExistente(correo) {
|
|
try {
|
|
const respuesta = await consultarCorreo(correo);
|
|
|
|
if (respuesta && respuesta.length > 0) {
|
|
// El correo existe
|
|
return true;
|
|
} else {
|
|
// El correo no existe
|
|
return false;
|
|
}
|
|
} catch (error) {
|
|
console.error('Error al consultar el correo:', error);
|
|
// Tratar el error según tu lógica, puedes decidir si detener el proceso o no
|
|
return false;
|
|
}
|
|
}
|
|
</script>
|
|
</body>
|
|
|
|
</html>
|