Correxiones sintaxis
This commit is contained in:
@@ -4,6 +4,7 @@ require_once __DIR__ . '/../helpers/env.php';
|
||||
require_once __DIR__ . '/../helpers/crypto.php';
|
||||
require_once __DIR__ . '/../helpers/session.php';
|
||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
||||
require_once __DIR__ . '/../helpers/bitacoras.php';
|
||||
|
||||
use PHPMailer\PHPMailer\PHPMailer;
|
||||
use PHPMailer\PHPMailer\Exception;
|
||||
@@ -30,12 +31,13 @@ function aprobarUsuarios()
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
$sql = "SELECT request_id, company_name, rfc, email, phone, request_date, opinion_file
|
||||
FROM solicitudes_importadores
|
||||
WHERE request_status = 'pending'
|
||||
ORDER BY request_date DESC";
|
||||
|
||||
$sql = "SELECT request_id, company_name, rfc, email, phone, request_date, opinion_file
|
||||
FROM solicitudes_importadores
|
||||
WHERE request_status = 'pending'
|
||||
ORDER BY request_date DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$solicitudes = [];
|
||||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$solicitudes[] = $row;
|
||||
@@ -47,6 +49,7 @@ function aprobarUsuarios()
|
||||
function aprobar_usuario()
|
||||
{
|
||||
$conn = getConnection();
|
||||
|
||||
$id = $_GET['id'] ?? null;
|
||||
|
||||
if (!$id || !is_numeric($id)) {
|
||||
@@ -106,10 +109,11 @@ function aprobar_usuario()
|
||||
$email_encrypt = encrypt($email);
|
||||
|
||||
// Insertar en usuarios_sistema y obtener ID en la misma consulta
|
||||
$sqlInsert = "INSERT INTO usuarios_sistema (nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por, preferencias_catalogos)
|
||||
$sqlInsert = "INSERT INTO usuarios_sistema
|
||||
(nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por, preferencias_catalogos)
|
||||
OUTPUT INSERTED.id_usuario
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?, 1)";
|
||||
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?, 1)
|
||||
";
|
||||
$stmtInsert = sqlsrv_query($conn, $sqlInsert, [
|
||||
$nombre_encrypt, $email_encrypt, $password_hash, $tipo, $_SESSION['usuario_id']
|
||||
]);
|
||||
@@ -126,12 +130,8 @@ function aprobar_usuario()
|
||||
throw new Exception("No se pudo obtener el ID del usuario creado. ID obtenido: " . var_export($idUsuarioRow, true));
|
||||
}
|
||||
|
||||
error_log("✓ Usuario creado exitosamente con ID: " . $id_usuario);
|
||||
|
||||
// Insertar en informacion_general
|
||||
$sqlInfo = "INSERT INTO informacion_general
|
||||
(id_usuario, nombre, rfc, correo, telefono)
|
||||
VALUES (?, ?, ?, ?, ?)";
|
||||
$sqlInfo = "INSERT INTO informacion_general (id_usuario, nombre, rfc, correo, telefono) VALUES (?, ?, ?, ?, ?)";
|
||||
$stmtInfo = sqlsrv_query($conn, $sqlInfo, [
|
||||
$id_usuario, $nombre, $rfc, $email, $telefono
|
||||
]);
|
||||
@@ -144,7 +144,8 @@ function aprobar_usuario()
|
||||
$sqlPref = "INSERT INTO preferencias_catalogos_usuario
|
||||
(id_usuario, locaciones, vinculacion, transportistas, transportes, choferes, proveedores,
|
||||
productos_frecuentes, solicitudes_importacion, expediente_electronico, configuracion, cerrar_sesion)
|
||||
VALUES (?, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)";
|
||||
VALUES (?, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
|
||||
";
|
||||
$stmtPref = sqlsrv_query($conn, $sqlPref, [$id_usuario]);
|
||||
|
||||
if (!$stmtPref) {
|
||||
@@ -152,9 +153,12 @@ function aprobar_usuario()
|
||||
}
|
||||
|
||||
// Actualizar solicitud
|
||||
$sqlUpdate = "UPDATE solicitudes_importadores
|
||||
SET request_status = 'approved', approval_date = GETDATE(), approved_by = ?
|
||||
WHERE request_id = ?";
|
||||
$sqlUpdate = "UPDATE solicitudes_importadores
|
||||
SET request_status = 'approved',
|
||||
approval_date = GETDATE(),
|
||||
approved_by = ?
|
||||
WHERE request_id = ?
|
||||
";
|
||||
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$_SESSION['usuario_id'], $id]);
|
||||
|
||||
if (!$stmtUpdate) {
|
||||
@@ -242,7 +246,13 @@ function altaUsuarios()
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
$sql = "SELECT * FROM usuarios_sistema WHERE activo = 1 ORDER BY creado_en DESC";
|
||||
$sql = "SELECT u.*, creador.nombre as nombre_creador
|
||||
FROM usuarios_sistema u
|
||||
LEFT JOIN usuarios_sistema creador
|
||||
ON u.creado_por = creador.id_usuario
|
||||
WHERE u.activo = 1
|
||||
ORDER BY u.creado_en DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$usuarios = [];
|
||||
@@ -293,9 +303,11 @@ function guardar_usuario()
|
||||
}
|
||||
|
||||
// 4. Insertar usuario
|
||||
$sqlInsert = "INSERT INTO usuarios_sistema (nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
||||
$sqlInsert = "INSERT INTO usuarios_sistema
|
||||
(nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
||||
OUTPUT INSERTED.id_usuario
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?)";
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?)
|
||||
";
|
||||
$params = [$nombre_encrypted, $email_encrypted, $password_hash, $tipo, $_SESSION['usuario_id']];
|
||||
$stmtInsert = sqlsrv_query($conn, $sqlInsert, $params);
|
||||
|
||||
@@ -309,9 +321,7 @@ function guardar_usuario()
|
||||
$id_usuario = $idUsuarioRow['id_usuario'] ?? null;
|
||||
|
||||
// 6. Insertar en informacion_general
|
||||
$sqlInfo = "INSERT INTO informacion_general
|
||||
(id_usuario, nombre, correo)
|
||||
VALUES (?, ?, ?)";
|
||||
$sqlInfo = "INSERT INTO informacion_general (id_usuario, nombre, correo) VALUES (?, ?, ?)";
|
||||
$stmtInfo = sqlsrv_query($conn, $sqlInfo, [$id_usuario, $nombre, $email]);
|
||||
|
||||
if (!$stmtInfo) {
|
||||
@@ -322,7 +332,8 @@ function guardar_usuario()
|
||||
$sqlPref = "INSERT INTO preferencias_catalogos_usuario
|
||||
(id_usuario, locaciones, vinculacion, transportistas, transportes, choferes, proveedores,
|
||||
productos_frecuentes, solicitudes_importacion, expediente_electronico, configuracion, cerrar_sesion)
|
||||
VALUES (?, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)";
|
||||
VALUES (?, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
|
||||
";
|
||||
$stmtPref = sqlsrv_query($conn, $sqlPref, [$id_usuario]);
|
||||
|
||||
if (!$stmtPref) {
|
||||
@@ -348,7 +359,7 @@ function guardar_usuario()
|
||||
|
||||
// Determinar el tipo de usuario para el mensaje
|
||||
$tipoUsuarioTexto = match($tipo) {
|
||||
'importador' => 'importador',
|
||||
'importador' => 'importador',
|
||||
'super_admin' => 'administrador'
|
||||
};
|
||||
|
||||
@@ -407,7 +418,14 @@ function usuariosInactivos()
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "SELECT * FROM usuarios_sistema WHERE activo = 0 ORDER BY creado_en DESC";
|
||||
|
||||
$sql = "SELECT u.*, creador.nombre as nombre_creador
|
||||
FROM usuarios_sistema u
|
||||
LEFT JOIN usuarios_sistema creador
|
||||
ON u.creado_por = creador.id_usuario
|
||||
WHERE u.activo = 0
|
||||
ORDER BY u.creado_en DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$usuarios = [];
|
||||
@@ -428,12 +446,13 @@ function aprobarAgencias()
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
$sql = "SELECT request_id, agencia_name, rfc, email, phone, request_date, opinion_file
|
||||
FROM solicitudes_agencias
|
||||
WHERE request_status = 'pending'
|
||||
ORDER BY request_date DESC";
|
||||
|
||||
$sql = "SELECT request_id, agencia_name, rfc, email, phone, direccion, request_date, opinion_file
|
||||
FROM solicitudes_agencias
|
||||
WHERE request_status = 'pending'
|
||||
ORDER BY request_date DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$solicitudes = [];
|
||||
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$solicitudes[] = $row;
|
||||
@@ -445,6 +464,7 @@ function aprobarAgencias()
|
||||
function aprobar_agencia()
|
||||
{
|
||||
$conn = getConnection();
|
||||
|
||||
$id = $_GET['id'] ?? null;
|
||||
$usuario_id = $_SESSION['usuario_id'];
|
||||
|
||||
@@ -489,8 +509,10 @@ function aprobar_agencia()
|
||||
$admin_email_encrypt = encrypt($admin_email);
|
||||
|
||||
// Insertar en agencias_aduanales
|
||||
$sqlInsert = "INSERT INTO agencias_aduanales (nombre_agencia, rfc_agencia, direccion, telefono, email, creado_en, creado_por)
|
||||
VALUES (?, ?, ?, ?, ?, GETDATE()), ?";
|
||||
$sqlInsert = "INSERT INTO agencias_aduanales
|
||||
(nombre_agencia, rfc_agencia, direccion, telefono, email, creado_en, creado_por)
|
||||
VALUES (?, ?, ?, ?, ?, GETDATE(), ?)
|
||||
";
|
||||
$stmtInsert = sqlsrv_query($conn, $sqlInsert, [
|
||||
$nombre_encrypt, $rfc, $direccion, $phone, $email_encrypt, $usuario_id
|
||||
]);
|
||||
@@ -510,8 +532,9 @@ function aprobar_agencia()
|
||||
}
|
||||
|
||||
// Insertar en usuarios_sistema
|
||||
$sqlInsert2 = "INSERT INTO usuarios_sistema (nombre, email, password_hash, tipo_usuario, activo, creado_en, dos factores, creado_por)
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE()), 0, ?";
|
||||
$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
|
||||
]);
|
||||
@@ -539,9 +562,7 @@ function aprobar_agencia()
|
||||
}
|
||||
|
||||
// Insertar en informacion_general
|
||||
$sqlInfo = "INSERT INTO informacion_general
|
||||
(id_usuario, nombre, correo)
|
||||
VALUES (?, ?, ?)";
|
||||
$sqlInfo = "INSERT INTO informacion_general (id_usuario, nombre, correo) VALUES (?, ?, ?)";
|
||||
$stmtInfo = sqlsrv_query($conn, $sqlInfo, [
|
||||
$id_usuario, $admin_name, $admin_email
|
||||
]);
|
||||
@@ -552,7 +573,9 @@ function aprobar_agencia()
|
||||
|
||||
// Actualizar solicitud
|
||||
$sqlUpdate = "UPDATE solicitudes_agencias
|
||||
SET request_status = 'approved', approval_date = GETDATE(), approved_by = ?
|
||||
SET request_status = 'approved',
|
||||
approval_date = GETDATE(),
|
||||
approved_by = ?
|
||||
WHERE request_id = ?";
|
||||
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$usuario_id, $id]);
|
||||
|
||||
@@ -616,6 +639,7 @@ function altaAgencias()
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
$sql = "SELECT * FROM agencias_aduanales ORDER BY creado_en DESC";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
@@ -638,12 +662,9 @@ function guardar_agencia()
|
||||
|
||||
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'] ?? '');
|
||||
@@ -653,20 +674,13 @@ 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");
|
||||
}
|
||||
|
||||
@@ -676,27 +690,21 @@ 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)
|
||||
OUTPUT INSERTED.id_usuario
|
||||
VALUES (?, ?, ?, 'admin_agencia', 1, GETDATE(), 0, ?);
|
||||
";
|
||||
|
||||
$paramsAdmin = [$nombre_admin_enc, $correo_admin_enc, $password_hash, $_SESSION['usuario_id']];
|
||||
$stmtAdmin = sqlsrv_query($conn, $sqlInsertAdmin, $paramsAdmin);
|
||||
$sqlInsertAdmin = "INSERT INTO usuarios_sistema
|
||||
(nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
||||
OUTPUT INSERTED.id_usuario
|
||||
VALUES (?, ?, ?, 'admin_agencia', 1, GETDATE(), 0, ?);
|
||||
";
|
||||
$paramsAdmin = [$nombre_admin_enc, $correo_admin_enc, $password_hash, $_SESSION['usuario_id']];
|
||||
$stmtAdmin = sqlsrv_query($conn, $sqlInsertAdmin, $paramsAdmin);
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -705,26 +713,20 @@ 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)
|
||||
OUTPUT INSERTED.id_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);
|
||||
$sqlInsertAgencia = "INSERT INTO agencias_aduanales
|
||||
(nombre_agencia, rfc_agencia, direccion, telefono, email, id_administrador, activo, creado_en, creado_por)
|
||||
OUTPUT INSERTED.id_agencia
|
||||
VALUES (?, ?, ?, ?, ?, ?, 1, GETDATE(), ?)
|
||||
";
|
||||
$paramsAgencia = [$nombre_agencia_enc, $rfc_agencia, $direccion, $telefono, $correo_agencia_enc, $id_admin, $_SESSION['usuario_id']];
|
||||
$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));
|
||||
}
|
||||
|
||||
@@ -733,36 +735,27 @@ 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);
|
||||
$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']];
|
||||
$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']);
|
||||
|
||||
@@ -804,7 +797,6 @@ 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());
|
||||
@@ -813,7 +805,6 @@ function guardar_agencia()
|
||||
}
|
||||
|
||||
// 8️⃣ Redirigir con éxito
|
||||
error_log("=== FIN EXITOSO guardar_agencia ===");
|
||||
header("Location: /IMPORTADORES/administrador/altaAgencias?success=created");
|
||||
exit;
|
||||
|
||||
@@ -825,13 +816,11 @@ function guardar_agencia()
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -844,7 +833,13 @@ function agenciasActivas()
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "SELECT * FROM agencias_aduanales ORDER BY creado_en DESC";
|
||||
|
||||
$sql = "SELECT aa.*, u.nombre as nombre_admin
|
||||
FROM agencias_aduanales aa
|
||||
INNER JOIN usuarios_sistema u
|
||||
ON aa.id_administrador = u.id_usuario
|
||||
ORDER BY creado_en DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql);
|
||||
|
||||
$agencias = [];
|
||||
@@ -864,7 +859,7 @@ function suspender()
|
||||
|
||||
$conn = getConnection();
|
||||
|
||||
$id = $_GET['id'] ?? null;
|
||||
$id = $_GET['id'] ?? null;
|
||||
|
||||
if (!$id || !is_numeric($id)) {
|
||||
header("Location: /IMPORTADORES/administrador/altaUsuarios?error=invalid_id");
|
||||
@@ -963,7 +958,7 @@ function reset_password()
|
||||
|
||||
$sqlEmail = "SELECT email FROM usuarios_sistema WHERE id_usuario = ?";
|
||||
$stmtEmail = sqlsrv_query($conn, $sqlEmail, [$id]);
|
||||
$row = sqlsrv_fetch_array($stmtEmail, SQLSRV_FETCH_ASSOC);
|
||||
$row = sqlsrv_fetch_array($stmtEmail, SQLSRV_FETCH_ASSOC);
|
||||
|
||||
$sql = "UPDATE usuarios_sistema SET password_hash = ? WHERE id_usuario = ?";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$passwordHash, $id]);
|
||||
@@ -980,7 +975,8 @@ function reset_password()
|
||||
exit;
|
||||
}
|
||||
|
||||
function enviar_password_directamente($email_encrypted, $pass) {
|
||||
function enviar_password_directamente($email_encrypted, $pass)
|
||||
{
|
||||
$email = decrypt($email_encrypted);
|
||||
|
||||
$mail = new PHPMailer(true);
|
||||
|
||||
@@ -41,7 +41,7 @@ function validar()
|
||||
if ($stmt && $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
|
||||
if (!$row['activo']) {
|
||||
registrarBitacora($conn, $row['id_usuario'], $email, $ip, 0, 'Usuario inactivo');
|
||||
registrarBitacora($row['id_usuario'], $email, $ip, 0, 'Usuario inactivo');
|
||||
$_SESSION['login_error'] = 'Tu usuario está inactivo.';
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
@@ -70,7 +70,7 @@ function validar()
|
||||
$stmtCodigo = sqlsrv_query($conn, $sqlCodigo, $paramsCodigo);
|
||||
|
||||
if (!$stmtCodigo) {
|
||||
registrarBitacora($conn, $row['id_usuario'], $email, $ip, 0, 'Error al generar código de verificación');
|
||||
registrarBitacora($row['id_usuario'], $email, $ip, 0, 'Error al generar código de verificación');
|
||||
$_SESSION['login_error'] = 'Error interno. Inténtalo de nuevo.';
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
@@ -88,7 +88,7 @@ function validar()
|
||||
$_SESSION['id_agencia_en_uso'] = $rowAg['id_agencia_en_uso'];
|
||||
}
|
||||
|
||||
registrarBitacora($conn, $row['id_usuario'], $email, $ip, 1, 'Login exitoso - Pendiente confirmación 2FA');
|
||||
registrarBitacora($row['id_usuario'], $email, $ip, 1, 'Login exitoso - Pendiente confirmación 2FA');
|
||||
|
||||
// Redirigir a confirmación de código
|
||||
header('Location: /IMPORTADORES/login/confirmar');
|
||||
@@ -104,7 +104,7 @@ function validar()
|
||||
$_SESSION['id_agencia_en_uso'] = $rowAg['id_agencia_en_uso'];
|
||||
}
|
||||
|
||||
registrarBitacora($conn, $row['id_usuario'], $email, $ip, 1, 'Login exitoso - Sin 2FA');
|
||||
registrarBitacora($row['id_usuario'], $email, $ip, 1, 'Login exitoso - Sin 2FA');
|
||||
|
||||
// Obtener el tipo de usuario para redirección
|
||||
$tipoUsuario = $_SESSION['tipo_usuario'] ?? 'importador';
|
||||
@@ -114,14 +114,14 @@ function validar()
|
||||
}
|
||||
|
||||
} else {
|
||||
registrarBitacora($conn, $row['id_usuario'], $email, $ip, 0, 'Contraseña incorrecta');
|
||||
registrarBitacora($row['id_usuario'], $email, $ip, 0, 'Contraseña incorrecta');
|
||||
$_SESSION['login_error'] = '❌ Contraseña incorrecta, intenta nuevamente.';
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
|
||||
} else {
|
||||
registrarBitacora($conn, null, $email, $ip, 0, 'Usuario no encontrado');
|
||||
registrarBitacora(null, $email, $ip, 0, 'Usuario no encontrado');
|
||||
$_SESSION['login_error'] = '❌ Correo no encontrado, debe registrarse primero.';
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
@@ -216,7 +216,7 @@ function confirmarAcceso()
|
||||
|
||||
// Verificar que el usuario tenga una sesión válida y pendiente de confirmación
|
||||
if (!$usuarioId || !$codigoIngresado || !($_SESSION['pendiente_confirmacion'] ?? false)) {
|
||||
registrarBitacora($conn, $usuarioId, $email, $ip, 0, 'Confirmación 2FA - Datos incompletos o sesión inválida');
|
||||
registrarBitacora($usuarioId, $email, $ip, 0, 'Confirmación 2FA - Datos incompletos o sesión inválida');
|
||||
$_SESSION['codigo_error'] = '❌ Datos incompletos o sesión inválida.';
|
||||
|
||||
// Limpiar sesión por seguridad
|
||||
@@ -231,7 +231,7 @@ function confirmarAcceso()
|
||||
$stmt = sqlsrv_query($conn, $sql, [$usuarioId, $codigoIngresado]);
|
||||
|
||||
if (!$stmt || !($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))) {
|
||||
registrarBitacora($conn, $usuarioId, $email, $ip, 0, 'Confirmación 2FA - Código incorrecto');
|
||||
registrarBitacora($usuarioId, $email, $ip, 0, 'Confirmación 2FA - Código incorrecto');
|
||||
$_SESSION['codigo_error'] = '❌ Código incorrecto.';
|
||||
header('Location: /IMPORTADORES/login/confirmar');
|
||||
exit;
|
||||
@@ -240,7 +240,7 @@ function confirmarAcceso()
|
||||
// Validar expiración
|
||||
$expiracion = $row['expiracion'];
|
||||
if ($expiracion instanceof DateTime && $expiracion->getTimestamp() < time()) {
|
||||
registrarBitacora($conn, $usuarioId, $email, $ip, 0, 'Confirmación 2FA - Código vencido');
|
||||
registrarBitacora($usuarioId, $email, $ip, 0, 'Confirmación 2FA - Código vencido');
|
||||
$_SESSION['codigo_error'] = '❌ El código ha expirado.';
|
||||
|
||||
// Limpiar sesión y redirigir al login
|
||||
@@ -250,7 +250,7 @@ function confirmarAcceso()
|
||||
}
|
||||
|
||||
// Código válido - Completar el login
|
||||
registrarBitacora($conn, $usuarioId, $email, $ip, 1, 'Confirmación 2FA exitosa - Login completado');
|
||||
registrarBitacora($usuarioId, $email, $ip, 1, 'Confirmación 2FA exitosa - Login completado');
|
||||
|
||||
$_SESSION['pendiente_confirmacion'] = false;
|
||||
$_SESSION['codigo_exito'] = '✅ Verificación de dos factores completada correctamente.';
|
||||
@@ -1057,7 +1057,7 @@ function cambiarPassword()
|
||||
|
||||
// Registrar en bitácora
|
||||
$ip = $_SERVER['REMOTE_ADDR'] ?? 'N/A';
|
||||
registrarBitacora($conn, $idUsuario, $email, $ip, 1, 'Cambio de contraseña por recuperación');
|
||||
registrarBitacora($idUsuario, $email, $ip, 1, 'Cambio de contraseña por recuperación');
|
||||
|
||||
// Enviar correo de confirmación
|
||||
try {
|
||||
|
||||
@@ -1,32 +1,58 @@
|
||||
<?php
|
||||
require_once __DIR__ . '/../../config/database.php';
|
||||
|
||||
function registrarBitacora($conn, $idUsuario, $email, $ip, $exito, $detalle)
|
||||
function registrarBitacora($idUsuario, $email, $ip, $exito, $detalle)
|
||||
{
|
||||
$conn = getConnection();
|
||||
if (!$conn) {
|
||||
error_log("❌ No se pudo establecer la conexión en registrarBitacora");
|
||||
return;
|
||||
}
|
||||
|
||||
$sql = "INSERT INTO bitacora_login (id_usuario, email, ip, exito, detalle)
|
||||
VALUES (?, ?, ?, ?, ?)";
|
||||
$params = [$idUsuario, $email, $ip, $exito, $detalle];
|
||||
sqlsrv_query($conn, $sql, $params);
|
||||
}
|
||||
|
||||
function registrar_bitacora_usuario($usuarioId, $accion, $descripcion)
|
||||
{
|
||||
$conn = getConnection();
|
||||
|
||||
$sql = "INSERT INTO bitacora_usuarios (usuario_id, accion, descripcion)
|
||||
VALUES (?, ?, ?)";
|
||||
$params = [$usuarioId, $accion, $descripcion];
|
||||
|
||||
sqlsrv_query($conn, $sql, $params);
|
||||
}
|
||||
|
||||
function registrar_bitacora_agencia($agenciaId, $nombreAgencia, $accion, $idAdmin)
|
||||
{
|
||||
$conn = getConnection();
|
||||
|
||||
$sql = "INSERT INTO bitacora_agencias (id_agencia, nombre, accion, realizado_por, fecha)
|
||||
VALUES (?, ?, ?, ?, GETDATE())";
|
||||
$params = [$agenciaId, $nombreAgencia, $accion, $idAdmin];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if (!$stmt) {
|
||||
error_log("Error al registrar bitácora de agencia: " . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
sqlsrv_close($conn);
|
||||
}
|
||||
|
||||
function registrar_bitacora_usuario($usuarioId, $accion, $descripcion)
|
||||
{
|
||||
$conn = getConnection();
|
||||
if (!$conn) {
|
||||
error_log("❌ No se pudo establecer la conexión en registrarBitacora");
|
||||
return;
|
||||
}
|
||||
|
||||
$sql = "INSERT INTO bitacora_usuarios (usuario_id, accion, descripcion)
|
||||
VALUES (?, ?, ?)";
|
||||
$params = [$usuarioId, $accion, $descripcion];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if (!$stmt) {
|
||||
error_log("Error al registrar bitácora de agencia: " . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
sqlsrv_close($conn);
|
||||
}
|
||||
|
||||
function registrar_bitacora_agencia($agenciaId, $nombreAgencia, $accion, $idAdmin)
|
||||
{
|
||||
$conn = getConnection();
|
||||
if (!$conn) {
|
||||
error_log("❌ No se pudo establecer la conexión en registrarBitacora");
|
||||
return;
|
||||
}
|
||||
|
||||
$sql = "INSERT INTO bitacora_agencias (id_agencia, nombre, accion, realizado_por, fecha)
|
||||
VALUES (?, ?, ?, ?, GETDATE())";
|
||||
$params = [$agenciaId, $nombreAgencia, $accion, $idAdmin];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if (!$stmt) {
|
||||
error_log("Error al registrar bitácora de agencia: " . print_r(sqlsrv_errors(), true));
|
||||
|
||||
@@ -89,13 +89,13 @@
|
||||
<?php foreach ($agencias as $ag): ?>
|
||||
<tr>
|
||||
<td><?= $ag['id_agencia'] ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($ag['nombre_agencia'])) ?></td>
|
||||
<td><?= htmlspecialchars($ag['rfc_agencia']) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($ag['email'])) ?></td>
|
||||
<td><?= htmlspecialchars($ag['telefono']) ?></td>
|
||||
<td><?= htmlspecialchars($ag['direccion']) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($ag['nombre_agencia'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars($ag['rfc_agencia'] ?? '') ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($ag['email'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars($ag['telefono'] ?? '') ?></td>
|
||||
<td><?= htmlspecialchars($ag['direccion'] ?? '') ?></td>
|
||||
<td><?= $ag['creado_en'] ? $ag['creado_en']->format('Y-m-d H:i') : '' ?></td>
|
||||
<td><?= htmlspecialchars($ag['id_administrador']) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($ag['nombre_admin'] ?? '')) ?></td>
|
||||
<td>
|
||||
<?php if (isset($ag['activo']) && $ag['activo'] == 1): ?>
|
||||
<a href="/IMPORTADORES/administrador/suspenderAgencia?id=<?= $ag['id_agencia'] ?>&success=1" class="btn btn-sm btn-danger mt-auto w-auto btn-animated">Suspender</a>
|
||||
|
||||
@@ -193,18 +193,18 @@
|
||||
</div>
|
||||
<div class="col-md-2 form-group-animated">
|
||||
<div class="form-floating-custom">
|
||||
<input name="password" type="password" class="form-control form-control input-pulse input-ripple" id="password" placeholder=" " required>
|
||||
<input name="password" type="password" class="form-control input-pulse input-ripple" id="password" placeholder=" " required>
|
||||
<label for="password" class="form-label">Contraseña *</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-2 form-group-animated">
|
||||
<div class="form-floating-custom">
|
||||
<select name="tipo_usuario" class="form-select select-pulse select-gradient select-arrow-rotate select-status" required>
|
||||
<option value="">Tipo</option>
|
||||
<select name="tipo_usuario" id="tipo" class="form-select select-pulse select-gradient select-arrow-rotate select-status" required>
|
||||
<option value=""></option>
|
||||
<option value="super_admin">Administrador General</option>
|
||||
<option value="importador">Importador</option>
|
||||
</select>
|
||||
<label for="tipo_usuario" class="form_label"></label>
|
||||
<label for="tipo" class="form-label">Tipo</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -233,10 +233,10 @@
|
||||
<?php foreach ($usuarios as $u): ?>
|
||||
<tr>
|
||||
<td><?= $u['id_usuario'] ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre'])) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['email'])) ?></td>
|
||||
<td><?= htmlspecialchars($u['tipo_usuario']) ?></td>
|
||||
<td><?= htmlspecialchars($u['creado_por']) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['email'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars($u['tipo_usuario'] ?? '') ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre_creador'] ?? '')) ?></td>
|
||||
<td><?= isset($u['creado_en']) && $u['creado_en'] instanceof DateTime ? $u['creado_en']->format('Y-m-d H:i') : '' ?></td>
|
||||
<td>
|
||||
<?php if (isset($u['activo']) && $u['activo'] == 1): ?>
|
||||
@@ -264,7 +264,7 @@
|
||||
|
||||
// Script para manejar las animaciones de validación
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const inputs = document.querySelectorAll('.form-control');
|
||||
const inputs = document.querySelectorAll('input.form-control, select.form_select');
|
||||
|
||||
inputs.forEach(input => {
|
||||
// Validación en tiempo real
|
||||
|
||||
@@ -88,10 +88,10 @@
|
||||
<?php foreach ($usuarios as $u): ?>
|
||||
<tr>
|
||||
<td><?= $u['id_usuario'] ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre'])) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['email'])) ?></td>
|
||||
<td><?= htmlspecialchars($u['tipo_usuario']) ?></td>
|
||||
<td><?= htmlspecialchars($u['creado_por']) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['email'] ?? '')) ?></td>
|
||||
<td><?= htmlspecialchars($u['tipo_usuario'] ?? '') ?></td>
|
||||
<td><?= htmlspecialchars(decrypt($u['nombre_creador'] ?? '')) ?></td>
|
||||
<td><?= isset($u['creado_en']) && $u['creado_en'] instanceof DateTime ? $u['creado_en']->format('Y-m-d H:i') : '' ?></td>
|
||||
<td>
|
||||
<?php if (isset($u['activo']) && $u['activo'] == 0): ?>
|
||||
|
||||
@@ -208,7 +208,7 @@
|
||||
</div>
|
||||
|
||||
<div class="col-md-6 form-group-animated">
|
||||
<label for="" class="form-label">Transportista *</label>
|
||||
<label for="" class="form-label">Transportista</label>
|
||||
<div class="form-floating-custom">
|
||||
<select name="id_transportista" id="transportista" class="form-select select-pulse select-gradient select-arrow-rotate select-status" required>
|
||||
<option value=""></option>
|
||||
@@ -218,7 +218,7 @@
|
||||
</option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<label for="trasportista" class="form-label">Transportista *</label>
|
||||
<label for="trasportista" class="form-label">Transportista</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -222,12 +222,12 @@
|
||||
<div class="col-md-4 form-group-animated">
|
||||
<div class="form-floating-custom">
|
||||
<select id="pais" name="pais" class="form-select select-pulse select-gradient select-arrow-rotate select-status" required>
|
||||
<option value="">Selecciona país</option>
|
||||
<option value=""></option>
|
||||
<?php foreach($paises as $p): ?>
|
||||
<option value="<?= $p['id_pais'] ?>"><?= htmlspecialchars($p['nombre']) ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<label for="pais" class="form-label">País *</label>
|
||||
<label for="pais" class="form-label">País</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -236,7 +236,7 @@
|
||||
<select id="entidad" name="entidad" class="form-select select-pulse select-gradient select-arrow-rotate select-status" required disabled>
|
||||
<option value="">Primero país…</option>
|
||||
</select>
|
||||
<label for="entidad" class="form-label">Entidad *</label>
|
||||
<label for="entidad" class="form-label">Entidad</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -245,11 +245,11 @@
|
||||
<select id="ciudad" name="ciudad" class="form-select select-pulse select-gradient select-arrow-rotate select-status" required disabled>
|
||||
<option value="">Primero estado…</option>
|
||||
</select>
|
||||
<label for="ciudad" class="form-label">Ciudad *</label>
|
||||
<label for="ciudad" class="form-label">Ciudad</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-8 form-group-animated">
|
||||
<div class="col-md-12 form-group-animated">
|
||||
<div class="form-floating-custom">
|
||||
<input name="domicilio" id="domicilio" type="text" class="form-control input-pulse input-gradient" maxlength="100" placeholder=" " required>
|
||||
<label for="domicilio" class="form-label">Domicilio *</label>
|
||||
@@ -373,7 +373,7 @@
|
||||
fetch(`/IMPORTADORES/transportistas/estados?pais=${pid}`)
|
||||
.then(r => { if (!r.ok) throw new Error('Error al cargar estados'); return r.json(); })
|
||||
.then(list => {
|
||||
estadoSelect.innerHTML = '<option value="">Selecciona estado</option>';
|
||||
estadoSelect.innerHTML = '<option value=""></option>';
|
||||
list.forEach(st => estadoSelect.add(new Option(st.nombre, st.id_estado)));
|
||||
estadoSelect.disabled = false;
|
||||
})
|
||||
@@ -392,7 +392,7 @@
|
||||
fetch(`/IMPORTADORES/transportistas/ciudades?estado=${eid}`)
|
||||
.then(r => { if (!r.ok) throw new Error('Error al cargar ciudades'); return r.json(); })
|
||||
.then(list => {
|
||||
ciudadSelect.innerHTML = '<option value="">Selecciona ciudad</option>';
|
||||
ciudadSelect.innerHTML = '<option value=""></option>';
|
||||
list.forEach(ct => ciudadSelect.add(new Option(ct.nombre, ct.id_ciudad)));
|
||||
ciudadSelect.disabled = false;
|
||||
})
|
||||
@@ -423,7 +423,7 @@
|
||||
});
|
||||
// Script para manejar las animaciones de validación
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const inputs = document.querySelectorAll('.form-control');
|
||||
const inputs = document.querySelectorAll('input.form-control, select.form_select');
|
||||
|
||||
inputs.forEach(input => {
|
||||
// Validación en tiempo real
|
||||
|
||||
Reference in New Issue
Block a user