CORRECCIONES - ALTA DE AGENCIAS - ADMINISTRADOR
This commit is contained in:
@@ -535,7 +535,7 @@ function aprobar_agencia()
|
||||
$sqlInsert2 = "INSERT INTO usuarios_sistema (nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?)
|
||||
";
|
||||
$stmtInsert2 = sqlsrv_query($conn, $sqlInsert, [$admin_name_encrypt, $admin_email_encrypt, $password_hash, $tipo, $usuario_id]);
|
||||
$stmtInsert2 = sqlsrv_query($conn, $sqlInsert2, [$admin_name_encrypt, $admin_email_encrypt, $password_hash, $tipo, $usuario_id]);
|
||||
|
||||
if (!$stmtInsert2) {
|
||||
die("❌ Error al crear usuario administrador: " . print_r(sqlsrv_errors(), true));
|
||||
@@ -561,9 +561,7 @@ function aprobar_agencia()
|
||||
|
||||
// Insertar en informacion_general
|
||||
$sqlInfo = "INSERT INTO informacion_general (id_usuario, nombre, correo) VALUES (?, ?, ?)";
|
||||
$stmtInfo = sqlsrv_query($conn, $sqlInfo, [
|
||||
$id_usuario, $admin_name, $admin_email
|
||||
]);
|
||||
$stmtInfo = sqlsrv_query($conn, $sqlInfo, [$id_usuario, $admin_name, $admin_email]);
|
||||
|
||||
if (!$stmtInfo) {
|
||||
die("❌ Error al insertar información general: " . print_r(sqlsrv_errors(), true));
|
||||
@@ -657,13 +655,22 @@ function guardar_agencia()
|
||||
exit;
|
||||
}
|
||||
|
||||
error_log("Usuario ID: " . $_SESSION['usuario_id']);
|
||||
error_log("Tipo usuario: " . $_SESSION['tipo_usuario']);
|
||||
|
||||
$conn = getConnection();
|
||||
if (!$conn) {
|
||||
throw new Exception("Error de conexión a la base de datos");
|
||||
}
|
||||
|
||||
try {
|
||||
if (!sqlsrv_begin_transaction($conn)) {
|
||||
error_log("ERROR: No se pudo iniciar la transacción");
|
||||
throw new Exception("Error al iniciar transacción");
|
||||
}
|
||||
|
||||
error_log("Transacción iniciada correctamente");
|
||||
|
||||
// 1️⃣ Captura y validación de datos
|
||||
$nombre_agencia = trim($_POST['nombre_agencia'] ?? '');
|
||||
$rfc_agencia = trim($_POST['rfc_agencia'] ?? '');
|
||||
@@ -673,13 +680,21 @@ function guardar_agencia()
|
||||
$nombre_admin = trim($_POST['nombre_admin'] ?? '');
|
||||
$correo_admin = trim($_POST['correo_admin'] ?? '');
|
||||
|
||||
error_log("Datos recibidos:");
|
||||
error_log("- Nombre agencia: " . $nombre_agencia);
|
||||
error_log("- RFC: " . $rfc_agencia);
|
||||
error_log("- Correo agencia: " . $correo_agencia);
|
||||
|
||||
|
||||
if (empty($nombre_agencia) || empty($rfc_agencia) || empty($correo_agencia) ||
|
||||
empty($telefono) || empty($direccion) || empty($nombre_admin) || empty($correo_admin)) {
|
||||
error_log("ERROR: Datos incompletos");
|
||||
throw new Exception("Datos incompletos");
|
||||
}
|
||||
|
||||
// 2️⃣ Verificar función de encriptación
|
||||
if (!function_exists('encrypt')) {
|
||||
error_log("ERROR: Función encrypt no existe");
|
||||
throw new Exception("Función de encriptación no disponible");
|
||||
}
|
||||
|
||||
@@ -689,10 +704,14 @@ function guardar_agencia()
|
||||
$nombre_admin_enc = encrypt($nombre_admin);
|
||||
$correo_admin_enc = encrypt($correo_admin);
|
||||
|
||||
error_log("Datos encriptados correctamente");
|
||||
|
||||
// 3️⃣ CREAR USUARIO ADMINISTRADOR Y OBTENER SU ID EN UNA SOLA CONSULTA
|
||||
$password_plain = bin2hex(random_bytes(5));
|
||||
$password_hash = password_hash($password_plain, PASSWORD_DEFAULT);
|
||||
|
||||
error_log("Password generado: " . $password_plain);
|
||||
|
||||
// ✅ SOLUCIÓN: INSERT con OUTPUT para obtener el ID inmediatamente
|
||||
$sqlInsertAdmin = "INSERT INTO usuarios_sistema
|
||||
(nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
||||
@@ -704,6 +723,7 @@ function guardar_agencia()
|
||||
|
||||
if (!$stmtAdmin) {
|
||||
$errors = sqlsrv_errors();
|
||||
error_log("ERROR SQL Admin: " . print_r($errors, true));
|
||||
throw new Exception("Error al crear administrador: " . print_r($errors, true));
|
||||
}
|
||||
|
||||
@@ -712,9 +732,12 @@ function guardar_agencia()
|
||||
$id_admin = $rowAdmin['id_usuario'] ?? null;
|
||||
|
||||
if (!$id_admin) {
|
||||
error_log("ERROR: ID de administrador es null");
|
||||
throw new Exception("No se pudo obtener ID de administrador");
|
||||
}
|
||||
|
||||
error_log("Usuario administrador creado exitosamente con ID: " . $id_admin);
|
||||
|
||||
// 4️⃣ CREAR AGENCIA Y OBTENER SU ID
|
||||
$sqlInsertAgencia = "INSERT INTO agencias_aduanales
|
||||
(nombre_agencia, rfc_agencia, direccion, telefono, email, id_administrador, activo, creado_en, creado_por)
|
||||
@@ -722,10 +745,13 @@ function guardar_agencia()
|
||||
VALUES (?, ?, ?, ?, ?, ?, 1, GETDATE(), ?)
|
||||
";
|
||||
$paramsAgencia = [$nombre_agencia_enc, $rfc_agencia, $direccion, $telefono, $correo_agencia_enc, $id_admin, $_SESSION['usuario_id']];
|
||||
error_log("Ejecutando SQL Agencia con ID admin: " . $id_admin);
|
||||
|
||||
$stmtAgencia = sqlsrv_query($conn, $sqlInsertAgencia, $paramsAgencia);
|
||||
|
||||
if (!$stmtAgencia) {
|
||||
$errors = sqlsrv_errors();
|
||||
error_log("ERROR SQL Agencia: " . print_r($errors, true));
|
||||
throw new Exception("Error al crear agencia: " . print_r($errors, true));
|
||||
}
|
||||
|
||||
@@ -734,27 +760,37 @@ function guardar_agencia()
|
||||
$id_agencia = $rowAgencia['id_agencia'] ?? null;
|
||||
|
||||
if (!$id_agencia) {
|
||||
error_log("ERROR: ID de agencia es null");
|
||||
throw new Exception("No se pudo obtener ID de agencia");
|
||||
}
|
||||
|
||||
error_log("Agencia creada exitosamente con ID: " . $id_agencia);
|
||||
|
||||
// 5️⃣ CREAR RELACIÓN AGENTE-AGENCIA
|
||||
$sqlInsertRelacion = "INSERT INTO agente_agencia
|
||||
(id_agente, id_agencia, fecha_asignacion, activo, asignado_por)
|
||||
VALUES (?, ?, GETDATE(), 1, ?)
|
||||
";
|
||||
$paramsRelacion = [$id_admin, $id_agencia, $_SESSION['usuario_id']];
|
||||
error_log("Creando relación agente-agencia");
|
||||
$stmtRelacion = sqlsrv_query($conn, $sqlInsertRelacion, $paramsRelacion);
|
||||
|
||||
if (!$stmtRelacion) {
|
||||
$errors = sqlsrv_errors();
|
||||
error_log("ERROR SQL Relación: " . print_r($errors, true));
|
||||
throw new Exception("Error al crear relación agente-agencia: " . print_r($errors, true));
|
||||
}
|
||||
|
||||
error_log("Relación agente-agencia creada exitosamente");
|
||||
|
||||
// 6️⃣ CONFIRMAR TRANSACCIÓN ✅
|
||||
if (!sqlsrv_commit($conn)) {
|
||||
error_log("ERROR: No se pudo confirmar la transacción");
|
||||
throw new Exception("Error al confirmar transacción");
|
||||
}
|
||||
|
||||
error_log("Transacción confirmada exitosamente");
|
||||
|
||||
// Registrar en bitácora
|
||||
registrar_bitacora_agencia($id_agencia, $nombre_agencia, 'CREACION', $_SESSION['usuario_id']);
|
||||
|
||||
@@ -796,6 +832,7 @@ function guardar_agencia()
|
||||
</div>";
|
||||
|
||||
$mail->send();
|
||||
error_log("Correo enviado exitosamente a: " . $correo_admin);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error al enviar correo: " . $e->getMessage());
|
||||
@@ -804,22 +841,24 @@ function guardar_agencia()
|
||||
}
|
||||
|
||||
// 8️⃣ Redirigir con éxito
|
||||
error_log("=== FIN EXITOSO guardar_agencia ===");
|
||||
header("Location: /IMPORTADORES/administrador/altaAgencias?success=created");
|
||||
exit;
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("ERROR CAPTURADO: " . $e->getMessage());
|
||||
if (!sqlsrv_rollback($conn)) {
|
||||
error_log("ERROR: No se pudo revertir la transacción");
|
||||
} else {
|
||||
error_log("Transacción revertida exitosamente");
|
||||
}
|
||||
|
||||
error_log("=== FIN CON ERROR guardar_agencia ===");
|
||||
header("Location: /IMPORTADORES/administrador/altaAgencias?error=save_failed");
|
||||
exit;
|
||||
} finally {
|
||||
if ($conn) {
|
||||
sqlsrv_close($conn);
|
||||
error_log("Conexión cerrada");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -837,6 +876,7 @@ function agenciasActivas()
|
||||
FROM agencias_aduanales aa
|
||||
INNER JOIN usuarios_sistema u
|
||||
ON aa.id_administrador = u.id_usuario
|
||||
WHERE aa.activo = 1
|
||||
ORDER BY creado_en DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
@@ -1040,7 +1080,7 @@ function suspenderAgencia()
|
||||
}
|
||||
|
||||
// Obtener el estado actual
|
||||
$sqlEstado = "SELECT activo FROM agencias_aduanles WHERE id_usuario = ?";
|
||||
$sqlEstado = "SELECT activo FROM agencias_aduanales WHERE id_agencia = ?";
|
||||
$stmtEstado = sqlsrv_query($conn, $sqlEstado, [$id]);
|
||||
|
||||
if (!$stmtEstado || !($row = sqlsrv_fetch_array($stmtEstado, SQLSRV_FETCH_ASSOC))) {
|
||||
@@ -1051,7 +1091,7 @@ function suspenderAgencia()
|
||||
$nuevoEstado = $row['activo'] ? 0 : 1;
|
||||
|
||||
// Actualizar estado
|
||||
$sqlUpdate = "UPDATE agencias_aduanles SET activo = ? WHERE id_usuario = ?";
|
||||
$sqlUpdate = "UPDATE agencias_aduanales SET activo = ? WHERE id_agencia = ?";
|
||||
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$nuevoEstado, $id]);
|
||||
|
||||
if (!$stmtUpdate) {
|
||||
|
||||
@@ -124,7 +124,7 @@
|
||||
<?php if (isset($_GET['success'])): ?>
|
||||
<script>
|
||||
<?php if ($_GET['success'] === 'status_deactivated'): ?>
|
||||
Swal.fire({ icon: 'success', title: 'Usuario desactivado', text: 'El usuario ha sido desactivado correctamente.', confirmButtonColor: '#198754' });
|
||||
Swal.fire({ icon: 'success', title: 'Agencia desactivada', text: 'La agencia ha sido desactivada correctamente.', confirmButtonColor: '#198754' });
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
@@ -134,11 +134,11 @@
|
||||
<?php if ($_GET['error'] === 'unauthorized'): ?>
|
||||
Swal.fire({ icon: 'error', title: 'No autorizado', text: 'No tienes permisos para realizar esta acción.', confirmButtonColor: '#dc3545' });
|
||||
<?php elseif ($_GET['error'] === 'invalid_id'): ?>
|
||||
Swal.fire({ icon: 'error', title: 'ID inválido', text: 'El identificador del usuario no es válido.', confirmButtonColor: '#dc3545' });
|
||||
Swal.fire({ icon: 'error', title: 'ID inválido', text: 'El identificador de la agencia no es válido.', confirmButtonColor: '#dc3545' });
|
||||
<?php elseif ($_GET['error'] === 'agencia_not_found'): ?>
|
||||
Swal.fire({ icon: 'error', title: 'Usuario no encontrado', text: 'No se encontró el usuario especificado.', confirmButtonColor: '#dc3545' });
|
||||
Swal.fire({ icon: 'error', title: 'Agencia no encontrada', text: 'No se encontró la agencia especificada.', confirmButtonColor: '#dc3545' });
|
||||
<?php elseif ($_GET['error'] === 'update_failed'): ?>
|
||||
Swal.fire({ icon: 'error', title: 'Error al actualizar', text: 'No se pudo actualizar el estado del usuario.', confirmButtonColor: '#dc3545' });
|
||||
Swal.fire({ icon: 'error', title: 'Error al actualizar', text: 'No se pudo actualizar el estado de la agencia.', confirmButtonColor: '#dc3545' });
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
<?php endif; ?>
|
||||
|
||||
@@ -280,7 +280,17 @@
|
||||
}
|
||||
// Si todas las validaciones pasan, el formulario se envía.
|
||||
this.submit();
|
||||
|
||||
// Validación del formulario
|
||||
let isValid = true;
|
||||
inputs.forEach(input => {
|
||||
if (!input.checkValidity()) {
|
||||
input.classList.add('shake');
|
||||
isValid = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Script para manejar las animaciones de validación
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const inputs = document.querySelectorAll('.form-control');
|
||||
@@ -304,30 +314,6 @@
|
||||
}, 500);
|
||||
});
|
||||
});
|
||||
|
||||
// Validación del formulario
|
||||
document.getElementById('formAltaAgencias').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
let isValid = true;
|
||||
inputs.forEach(input => {
|
||||
if (!input.checkValidity()) {
|
||||
input.classList.add('shake');
|
||||
isValid = false;
|
||||
}
|
||||
});
|
||||
|
||||
if (isValid) {
|
||||
// Aquí puedes agregar tu lógica de envío
|
||||
Swal.fire({
|
||||
icon: 'success',
|
||||
title: '¡Éxito!',
|
||||
text: 'Agencia registrada correctamente',
|
||||
showConfirmButton: false,
|
||||
timer: 1500
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -335,7 +321,7 @@
|
||||
<script>
|
||||
<?php if ($_GET['success'] === 'created'): ?>
|
||||
Swal.fire({ icon: 'success', title: 'Agencia registrada',
|
||||
text: 'La agencia adunal se ha registrada correctamente y se ha enviado un correo con las credenciales de acceso al administrador.',
|
||||
text: 'La agencia aduanal se ha registrada correctamente y se ha enviado un correo con las credenciales de acceso al administrador.',
|
||||
confirmButtonColor: '#198754' });
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
|
||||
@@ -8,6 +8,10 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
|
||||
<link href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
|
||||
<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
|
||||
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
|
||||
<!-- Font Awesome -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
|
||||
<!-- Animate.css para animaciones adicionales -->
|
||||
@@ -106,10 +110,6 @@
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<tr>
|
||||
<td colspan="8" class="text-center">No hay agencias registradas aún.</td>
|
||||
</tr>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
@@ -117,5 +117,16 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
$(document).ready(function () {
|
||||
$('#tabla-agencias-pendientes').DataTable({
|
||||
order: [],
|
||||
language: {
|
||||
url: 'https://cdn.datatables.net/plug-ins/1.13.4/i18n/es-ES.json'
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user