Aprobación de Agencias
This commit is contained in:
@@ -463,13 +463,14 @@ function aprobarAgencias()
|
||||
|
||||
function aprobar_agencia()
|
||||
{
|
||||
$conn = getConnection();
|
||||
$conn = getConnection();
|
||||
|
||||
$id = $_GET['id'] ?? null;
|
||||
$usuario_id = $_SESSION['usuario_id'];
|
||||
|
||||
if (!$id || !is_numeric($id)) {
|
||||
die("❌ ID inválido.");
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=invalid_id");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Obtener la solicitud
|
||||
@@ -477,8 +478,9 @@ function aprobar_agencia()
|
||||
$stmt = sqlsrv_query($conn, $sql, [$id]);
|
||||
$solicitud = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||
|
||||
if (!$solicitud) {
|
||||
die("❌ Solicitud no encontrada.");
|
||||
if (!$solicitud) {
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=invalid_request");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Validar que no haya sido aprobada ya
|
||||
@@ -511,6 +513,7 @@ function aprobar_agencia()
|
||||
// Insertar en agencias_aduanales
|
||||
$sqlInsert = "INSERT INTO agencias_aduanales
|
||||
(nombre_agencia, rfc_agencia, direccion, telefono, email, creado_en, creado_por)
|
||||
OUTPUT INSERTED.id_agencia
|
||||
VALUES (?, ?, ?, ?, ?, GETDATE(), ?)
|
||||
";
|
||||
$stmtInsert = sqlsrv_query($conn, $sqlInsert, [
|
||||
@@ -518,37 +521,38 @@ function aprobar_agencia()
|
||||
]);
|
||||
|
||||
if (!$stmtInsert) {
|
||||
die("❌ Error al crear agencia: " . print_r(sqlsrv_errors(), true));
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=save_agencia_failed");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Obtener ID de la agencia recién creada
|
||||
$sqlGetAgenciaId = "SELECT SCOPE_IDENTITY() AS id_agencia";
|
||||
$stmtGetAgenciaId = sqlsrv_query($conn, $sqlGetAgenciaId);
|
||||
$agenciaIdRow = sqlsrv_fetch_array($stmtGetAgenciaId, SQLSRV_FETCH_ASSOC);
|
||||
$id_agencia = $agenciaIdRow['id_agencia'] ?? null;
|
||||
$agenciaIdRow = sqlsrv_fetch_array($stmtInsert, SQLSRV_FETCH_ASSOC);
|
||||
$id_agencia = $agenciaIdRow['id_agencia'] ?? null;
|
||||
|
||||
if (!$id_agencia) {
|
||||
die("❌ No se pudo obtener el ID de la agencia recién creada.");
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=get_id_failed");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Insertar en usuarios_sistema
|
||||
$sqlInsert2 = "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, ?)
|
||||
";
|
||||
$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));
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=error_user");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Obtener ID del nuevo usuario
|
||||
$sqlGetId = "SELECT SCOPE_IDENTITY() AS id_usuario";
|
||||
$stmtGetId = sqlsrv_query($conn, $sqlGetId);
|
||||
$idUsuarioRow = sqlsrv_fetch_array($stmtGetId, SQLSRV_FETCH_ASSOC);
|
||||
$idUsuarioRow = sqlsrv_fetch_array($stmtInsert2, SQLSRV_FETCH_ASSOC);
|
||||
$id_usuario = $idUsuarioRow['id_usuario'] ?? null;
|
||||
|
||||
if (!$id_usuario) {
|
||||
die("❌ No se pudo obtener el ID del usuario recién creado.");
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=error_id");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Actualizar agencia con el ID del administrador
|
||||
@@ -556,7 +560,8 @@ function aprobar_agencia()
|
||||
$stmtUpdateAgencia = sqlsrv_query($conn, $sqlUpdateAgencia, [$id_usuario, $id_agencia]);
|
||||
|
||||
if (!$stmtUpdateAgencia) {
|
||||
die("❌ Error al actualizar agencia con administrador: " . print_r(sqlsrv_errors(), true));
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=update_failed");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Insertar en informacion_general
|
||||
@@ -564,7 +569,8 @@ function aprobar_agencia()
|
||||
$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));
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=update_failed");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Actualizar solicitud
|
||||
@@ -577,7 +583,8 @@ function aprobar_agencia()
|
||||
$stmtUpdate = sqlsrv_query($conn, $sqlUpdate, [$usuario_id, $id]);
|
||||
|
||||
if (!$stmtUpdate) {
|
||||
die("❌ Error al actualizar solicitud: " . print_r(sqlsrv_errors(), true));
|
||||
header("Location: /IMPORTADORES/administrador/aprobarAgencias?error=update_request_failed");
|
||||
exit;
|
||||
}
|
||||
|
||||
// Enviar correo a la agencia
|
||||
@@ -624,7 +631,7 @@ function aprobar_agencia()
|
||||
// Registrar en bitácora
|
||||
registrar_bitacora_agencia($id_agencia, $nombre, 'CREACION', $usuario_id);
|
||||
|
||||
header("Location: /IMPORTADORES/administrador/agenciasActivas");
|
||||
header("Location: /IMPORTADORES/administrador/agenciasActivas?success=created");
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
@@ -72,8 +72,6 @@ function alta()
|
||||
FROM agente_agencia aa
|
||||
INNER JOIN usuarios_sistema u
|
||||
ON aa.id_agente = u.id_usuario
|
||||
INNER JOIN agencias_aduanales a
|
||||
ON aa.id_agente = a.id_administrador
|
||||
LEFT JOIN usuarios_sistema creador
|
||||
ON u.creado_por = creador.id_usuario
|
||||
WHERE aa.id_agencia = ?
|
||||
@@ -108,6 +106,12 @@ function guardarAgente()
|
||||
$conn = getConnection();
|
||||
|
||||
try {
|
||||
// === AGREGADO: LOG DE DEPURACIÓN ===
|
||||
error_log("=== INICIO DEBUG guardarAgente ===");
|
||||
error_log("POST data: " . print_r($_POST, true));
|
||||
error_log("SESSION usuario_id: " . $_SESSION['usuario_id']);
|
||||
error_log("SESSION tipo_usuario: " . $_SESSION['tipo_usuario']);
|
||||
|
||||
if (!sqlsrv_begin_transaction($conn)) {
|
||||
error_log("ERROR: No se pudo iniciar la transacción");
|
||||
throw new Exception("Error al iniciar transacción");
|
||||
@@ -121,13 +125,25 @@ function guardarAgente()
|
||||
$password = $_POST['password'] ?? '';
|
||||
$tipo = $_POST['tipo_usuario'] ?? '';
|
||||
|
||||
// === AGREGADO: VALIDACIÓN DETALLADA ===
|
||||
error_log("Datos capturados:");
|
||||
error_log("nombre: '$nombre'");
|
||||
error_log("email: '$email'");
|
||||
error_log("password: " . (empty($password) ? 'VACÍO' : 'NO VACÍO'));
|
||||
error_log("tipo: '$tipo'");
|
||||
|
||||
if (empty($nombre) || empty($email) || empty($password) || empty($tipo)) {
|
||||
error_log("ERROR: Datos incompletos");
|
||||
error_log("nombre vacío: " . (empty($nombre) ? 'SÍ' : 'NO'));
|
||||
error_log("email vacío: " . (empty($email) ? 'SÍ' : 'NO'));
|
||||
error_log("password vacío: " . (empty($password) ? 'SÍ' : 'NO'));
|
||||
error_log("tipo vacío: " . (empty($tipo) ? 'SÍ' : 'NO'));
|
||||
header("Location: /IMPORTADORES/agencias/alta?error=invalid_data");
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($tipo !== 'agente_aduanal') {
|
||||
error_log("DEBUG 5: Tipo de usuario inválido: $tipo");
|
||||
error_log("ERROR: Tipo de usuario inválido: '$tipo'");
|
||||
header("Location: /IMPORTADORES/agencias/alta?error=invalid_user_type");
|
||||
exit;
|
||||
}
|
||||
@@ -137,15 +153,27 @@ function guardarAgente()
|
||||
$email_encrypted = encrypt($email);
|
||||
$password_hash = password_hash($password, PASSWORD_DEFAULT);
|
||||
|
||||
error_log("Datos encriptados exitosamente");
|
||||
|
||||
// 3. Validar duplicado por email encriptado
|
||||
$sqlCheck = "SELECT COUNT(*) AS total FROM usuarios_sistema WHERE email = ?";
|
||||
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$email_encrypted]);
|
||||
$rowCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
||||
|
||||
if ($stmtCheck === false) {
|
||||
error_log("ERROR: Fallo en consulta de duplicado");
|
||||
error_log(print_r(sqlsrv_errors(), true));
|
||||
throw new Exception("Error al verificar duplicado");
|
||||
}
|
||||
|
||||
$rowCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
||||
if ($rowCheck['total'] > 0) {
|
||||
error_log("ERROR: Email ya existe");
|
||||
header("Location: /IMPORTADORES/agencias/alta?error=email_exists");
|
||||
exit;
|
||||
}
|
||||
|
||||
error_log("Validación de duplicado pasada");
|
||||
|
||||
// 4. Insertar usuario
|
||||
$sqlInsert = "INSERT INTO usuarios_sistema
|
||||
(nombre, email, password_hash, tipo_usuario, activo, creado_en, dos_factores, creado_por)
|
||||
@@ -153,10 +181,20 @@ function guardarAgente()
|
||||
VALUES (?, ?, ?, ?, 1, GETDATE(), 0, ?)
|
||||
";
|
||||
$params = [$nombre_encrypted, $email_encrypted, $password_hash, $tipo, $_SESSION['usuario_id']];
|
||||
|
||||
error_log("Parámetros para INSERT:");
|
||||
error_log("nombre_encrypted: " . (empty($nombre_encrypted) ? 'VACÍO' : 'OK'));
|
||||
error_log("email_encrypted: " . (empty($email_encrypted) ? 'VACÍO' : 'OK'));
|
||||
error_log("password_hash: " . (empty($password_hash) ? 'VACÍO' : 'OK'));
|
||||
error_log("tipo: '$tipo'");
|
||||
error_log("creado_por: " . $_SESSION['usuario_id']);
|
||||
|
||||
$stmtInsert = sqlsrv_query($conn, $sqlInsert, $params);
|
||||
|
||||
if ($stmtInsert === false) {
|
||||
error_log("ERROR: Fallo al insertar usuario");
|
||||
error_log("SQL: $sqlInsert");
|
||||
error_log("Errores SQL Server:");
|
||||
error_log(print_r(sqlsrv_errors(), true));
|
||||
throw new Exception("Error al insertar usuario");
|
||||
}
|
||||
@@ -166,41 +204,67 @@ function guardarAgente()
|
||||
|
||||
if (!$id_usuario) {
|
||||
error_log("ERROR: No se obtuvo id_usuario tras el insert");
|
||||
error_log("idUsuarioRow: " . print_r($idUsuarioRow, true));
|
||||
throw new Exception("Error al obtener ID del nuevo usuario");
|
||||
}
|
||||
|
||||
// 6. Obtener la agencia del administrador actual
|
||||
error_log("Usuario insertado exitosamente con ID: $id_usuario");
|
||||
|
||||
// 5. Obtener la agencia del administrador actual
|
||||
$sqlAgencia = "SELECT id_agencia FROM agencias_aduanales WHERE id_administrador = ?";
|
||||
$stmtAgencia = sqlsrv_query($conn, $sqlAgencia, [$_SESSION['usuario_id']]);
|
||||
$agenciaRow = sqlsrv_fetch_array($stmtAgencia, SQLSRV_FETCH_ASSOC);
|
||||
$id_agencia = $agenciaRow['id_agencia'] ?? null;
|
||||
|
||||
if ($stmtAgencia === false) {
|
||||
error_log("ERROR: Fallo al consultar agencia");
|
||||
error_log(print_r(sqlsrv_errors(), true));
|
||||
throw new Exception("Error al consultar agencia");
|
||||
}
|
||||
|
||||
$agenciaRow = sqlsrv_fetch_array($stmtAgencia, SQLSRV_FETCH_ASSOC);
|
||||
$id_agencia = $agenciaRow['id_agencia'] ?? null;
|
||||
|
||||
if (!$id_agencia) {
|
||||
error_log("ERROR: No se encontró agencia para el admin_agencia con id_usuario=" . $_SESSION['usuario_id']);
|
||||
error_log("agenciaRow: " . print_r($agenciaRow, true));
|
||||
throw new Exception("No se encontró agencia asociada al administrador");
|
||||
}
|
||||
|
||||
// 7. Crear la relación agente-agencia
|
||||
error_log("Agencia encontrada con ID: $id_agencia");
|
||||
|
||||
// 6. Crear la relación agente-agencia
|
||||
$sqlRelacion = "INSERT INTO agente_agencia
|
||||
(id_agente, id_agencia, fecha_asignacion, activo, asignado_por)
|
||||
VALUES (?, ?, GETDATE(), 1, ?)
|
||||
";
|
||||
$paramsRelacion = [$id_usuario, $id_agencia, $_SESSION['usuario_id']];
|
||||
$stmtRelacion = sqlsrv_query($conn, $sqlRelacion, $paramsRelacion);
|
||||
|
||||
error_log("Parámetros para relación agente-agencia:");
|
||||
error_log("id_agente: $id_usuario");
|
||||
error_log("id_agencia: $id_agencia");
|
||||
error_log("asignado_por: " . $_SESSION['usuario_id']);
|
||||
|
||||
$stmtRelacion = sqlsrv_query($conn, $sqlRelacion, $paramsRelacion);
|
||||
|
||||
if ($stmtRelacion === false) {
|
||||
error_log("ERROR: No se pudo insertar la relación agente-agencia");
|
||||
error_log("SQL: $sqlRelacion");
|
||||
error_log("Errores SQL Server:");
|
||||
error_log(print_r(sqlsrv_errors(), true));
|
||||
throw new Exception("Error al guardar relación agente-agencia");
|
||||
}
|
||||
|
||||
// 8. CONFIRMAR TRANSACCIÓN ✅
|
||||
error_log("Relación agente-agencia creada exitosamente");
|
||||
|
||||
// 7. CONFIRMAR TRANSACCIÓN ✅
|
||||
if (!sqlsrv_commit($conn)) {
|
||||
error_log("ERROR: No se pudo confirmar la transacción");
|
||||
error_log(print_r(sqlsrv_errors(), true));
|
||||
throw new Exception("Error al confirmar transacción");
|
||||
}
|
||||
|
||||
// 9. Enviar correo de bienvenida
|
||||
error_log("Transacción confirmada exitosamente");
|
||||
|
||||
// 8. Enviar correo de bienvenida
|
||||
if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
|
||||
$mail = new PHPMailer(true);
|
||||
try {
|
||||
@@ -253,25 +317,30 @@ function guardarAgente()
|
||||
</div>";
|
||||
|
||||
$mail->send();
|
||||
error_log("Correo enviado exitosamente");
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("Error al enviar correo: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 10. Redirigir con mensaje de éxito
|
||||
error_log("=== FIN EXITOSO guardarAgente ===");
|
||||
// 9. Redirigir con mensaje de éxito
|
||||
header("Location: /IMPORTADORES/agencias/alta?success=created");
|
||||
exit;
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log("ERROR CAPTURADO: " . $e->getMessage());
|
||||
error_log("Stack trace: " . $e->getTraceAsString());
|
||||
|
||||
if (!sqlsrv_rollback($conn)) {
|
||||
error_log("ERROR: No se pudo revertir la transacción");
|
||||
error_log(print_r(sqlsrv_errors(), true));
|
||||
} else {
|
||||
error_log("Transacción revertida exitosamente");
|
||||
}
|
||||
|
||||
error_log("=== FIN CON ERROR guardar_agencia ===");
|
||||
error_log("=== FIN CON ERROR guardarAgente ===");
|
||||
header("Location: /IMPORTADORES/agencias/alta?error=save_failed");
|
||||
exit;
|
||||
} finally {
|
||||
|
||||
@@ -241,7 +241,7 @@ function guardar()
|
||||
sqlsrv_free_stmt($stmt);
|
||||
sqlsrv_close($conn);
|
||||
|
||||
header("Location: /IMPORTADORES/patente/lista?success=1");
|
||||
header("Location: /IMPORTADORES/patente/lista?created=ok");
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -317,13 +317,32 @@ function actualizar()
|
||||
$curp = trim($_POST['curp'] ?? '');
|
||||
$razon_social = trim($_POST['razon_social'] ?? '');
|
||||
$id_usuario = $_SESSION['usuario_id'];
|
||||
$tipo_usuario = $_SESSION['tipo_usuario'];
|
||||
|
||||
// ✅ NUEVO: Obtener la agencia actual del usuario
|
||||
$stmt = sqlsrv_query($conn, "SELECT id_agencia FROM dbo.agente_agencia WHERE id_agente = ?", [$id_usuario]);
|
||||
|
||||
// Obtener id_agencia del usuario actual
|
||||
$id_agencia = null;
|
||||
if ($stmt && $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$id_agencia = $row['id_agencia'];
|
||||
if ($tipo_usuario === 'agente_aduanal' || $tipo_usuario === 'admin_agencia') {
|
||||
$stmt = sqlsrv_query($conn, "SELECT id_agencia FROM dbo.agente_agencia WHERE id_agente = ?", [$id_usuario]);
|
||||
if ($stmt && $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$id_agencia = $row['id_agencia'];
|
||||
}
|
||||
}
|
||||
|
||||
if (!$id_agencia) {
|
||||
die("❌ No se pudo determinar la agencia del usuario.");
|
||||
}
|
||||
|
||||
// Verificar que el registro existe y pertenece a la agencia del usuario
|
||||
$sqlVerificar = "SELECT COUNT(*) as count FROM dbo.agentes_aduanales WHERE id_agente = ? AND id_agencia = ?";
|
||||
$stmtVerificar = sqlsrv_query($conn, $sqlVerificar, [$id_agente, $id_agencia]);
|
||||
|
||||
if ($stmtVerificar === false) {
|
||||
die("❌ Error al verificar el registro: " . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
$row = sqlsrv_fetch_array($stmtVerificar, SQLSRV_FETCH_ASSOC);
|
||||
if ($row['count'] == 0) {
|
||||
die("❌ El registro no existe o no tienes permisos para editarlo.");
|
||||
}
|
||||
|
||||
$mf_nombre = trim($_POST['mf_nombre'] ?? '');
|
||||
@@ -351,6 +370,7 @@ function actualizar()
|
||||
$vae_final = trim($_POST['vae_final'] ?? '');
|
||||
$vae_siguiente = trim($_POST['vae_siguiente'] ?? '');
|
||||
|
||||
// Validaciones
|
||||
if (!$id_agente || empty($aduana) || empty($patente) || empty($agente_aduanal) || empty($rfc) || empty($curp) || empty($razon_social)) {
|
||||
die("❌ Datos inválidos o incompletos.");
|
||||
}
|
||||
@@ -360,19 +380,16 @@ function actualizar()
|
||||
if (strlen($rfc) > 13) die("❌ El RFC no puede exceder 13 caracteres.");
|
||||
if (strlen($curp) > 18) die("❌ El CURP no puede exceder 18 caracteres.");
|
||||
|
||||
// Validar duplicado (excepto el propio id)
|
||||
$sqlCheck = "SELECT COUNT(*) as count FROM dbo.agentes_aduanales WHERE aduana = ? AND patente = ? AND id_usuario = ? AND id_agente != ?";
|
||||
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$aduana, $patente, $id_usuario, $id_agente]);
|
||||
// Validar duplicado
|
||||
$sqlCheck = "SELECT COUNT(*) as count FROM dbo.agentes_aduanales WHERE aduana = ? AND patente = ? AND id_agencia = ? AND id_agente != ?";
|
||||
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$aduana, $patente, $id_agencia, $id_agente]);
|
||||
|
||||
if ($stmtCheck === false) die("❌ Error al verificar duplicados.");
|
||||
|
||||
$row = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
||||
|
||||
if ($row['count'] > 0) die("❌ Ya existe un agente aduanal con esta combinación de aduana y patente.");
|
||||
|
||||
sqlsrv_free_stmt($stmtCheck);
|
||||
|
||||
// Convertir valores vacíos a NULL para la base de datos
|
||||
// Convertir valores vacíos a NULL
|
||||
$vp_inicio = empty($vp_inicio) ? null : $vp_inicio;
|
||||
$vp_final = empty($vp_final) ? null : $vp_final;
|
||||
$vp_siguiente = empty($vp_siguiente) ? null : $vp_siguiente;
|
||||
@@ -399,7 +416,7 @@ function actualizar()
|
||||
vcc_inicio = ?, vcc_final = ?, vcc_siguiente = ?,
|
||||
vae_inicio = ?, vae_final = ?, vae_siguiente = ?, id_agencia = ?
|
||||
WHERE id_agente = ?
|
||||
AND id_usuario = ?
|
||||
AND id_agencia = ?
|
||||
";
|
||||
$params = [
|
||||
$aduana, $patente, $agente_aduanal, $rfc, $curp, $razon_social,
|
||||
@@ -409,11 +426,19 @@ function actualizar()
|
||||
$vat_pb_inicio, $vat_pb_final, $vat_pb_siguiente,
|
||||
$vcc_inicio, $vcc_final, $vcc_siguiente,
|
||||
$vae_inicio, $vae_final, $vae_siguiente, $id_agencia,
|
||||
$id_agente, $id_usuario
|
||||
$id_agente, $id_agencia
|
||||
];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
|
||||
if ($stmt === false) die("❌ Error al actualizar agente aduanal.");
|
||||
if ($stmt === false) {
|
||||
die("❌ Error al actualizar: " . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
$rows_affected = sqlsrv_rows_affected($stmt);
|
||||
|
||||
if ($rows_affected === 0) {
|
||||
die("❌ No se actualizó ningún registro. Verifica los datos.");
|
||||
}
|
||||
|
||||
sqlsrv_free_stmt($stmt);
|
||||
sqlsrv_close($conn);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
<?php
|
||||
// app/controllers/proveedores.php
|
||||
require_once __DIR__ . '/../helpers/session.php';
|
||||
require_once __DIR__ . '/../../config/database.php';
|
||||
// 1) Composer autoload (phpdotenv y demás libs)
|
||||
@@ -28,11 +29,11 @@ function getApiToken(): ?string
|
||||
|
||||
// 2) Sí o sí hacemos login en la API
|
||||
$url = rtrim($_ENV['API_URL'] ?? '', '/') . '/auth/login';
|
||||
$user = $_ENV['API_USER'] ?? '';
|
||||
$pass = $_ENV['API_PASS'] ?? '';
|
||||
$user = $_ENV['API_USER'] ?? '';
|
||||
$pass = $_ENV['API_PASS'] ?? '';
|
||||
$body = json_encode(['username' => $user, 'password' => $pass]);
|
||||
|
||||
error_log("[getApiToken] POST $url → $body");
|
||||
error_log("[getApiToken] POST $url");
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
@@ -46,7 +47,7 @@ function getApiToken(): ?string
|
||||
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
error_log("[getApiToken] HTTP $http → $resp");
|
||||
error_log("[getApiToken] HTTP $http");
|
||||
|
||||
if ($http === 200 && ($data = json_decode($resp, true)) && !empty($data['token'])) {
|
||||
// 3) Guardamos token y tiempo actual
|
||||
@@ -87,62 +88,82 @@ function ajax_lista()
|
||||
$token = getApiToken();
|
||||
if (!$token) {
|
||||
error_log('[ajax_lista] Sin token válido');
|
||||
// Devolvemos estructura vacía
|
||||
echo json_encode(['data' => []]);
|
||||
echo json_encode(['data' => [], 'error' => 'No se pudo obtener token de autenticación']);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) Construimos la URL de la API
|
||||
// CORRECCIÓN: Usar la misma estructura de URL que en otras funciones
|
||||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||||
$url = $apiBase . '/proveedores';
|
||||
$url = $apiBase . '/api/proveedores'; // Cambié para que sea consistente
|
||||
error_log("[ajax_lista] GET $url");
|
||||
|
||||
// 4) Ejecutamos cURL
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Accept: application/json'],
|
||||
// CORRECCIÓN: Agregar "Bearer" al token
|
||||
CURLOPT_HTTPHEADER => ["Authorization: Bearer $token", 'Accept: application/json'],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
CURLOPT_TIMEOUT => 10, // Aumenté el timeout
|
||||
]);
|
||||
$resp = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$curlError = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
error_log("[ajax_lista] HTTP $status → $resp");
|
||||
error_log("[ajax_lista] HTTP $status");
|
||||
|
||||
// MEJORA: Verificar errores de cURL
|
||||
if ($curlError) {
|
||||
error_log("[ajax_lista] cURL Error: $curlError");
|
||||
echo json_encode(['data' => [], 'error' => 'Error de conexión con la API']);
|
||||
return;
|
||||
}
|
||||
|
||||
// MEJORA: Mejor manejo de errores
|
||||
if ($status !== 200) {
|
||||
error_log("[ajax_lista] Error HTTP $status: $resp");
|
||||
echo json_encode(['data' => [], 'error' => "Error HTTP $status"]);
|
||||
return;
|
||||
}
|
||||
|
||||
$json = json_decode($resp, true);
|
||||
if (!is_array($json)) {
|
||||
error_log("[ajax_lista] Respuesta no es un array válido: $resp");
|
||||
echo json_encode(['data' => [], 'error' => 'Respuesta inválida de la API']);
|
||||
return;
|
||||
}
|
||||
|
||||
error_log("[ajax_lista] Procesando " . count($json) . " proveedores");
|
||||
|
||||
// 5) Parseamos y formateamos
|
||||
$dataList = [];
|
||||
if ($status === 200 && ($json = json_decode($resp, true)) && is_array($json)) {
|
||||
foreach ($json as $p) {
|
||||
$clave = htmlspecialchars($p['Clave'] ?? '', ENT_QUOTES);
|
||||
foreach ($json as $p) {
|
||||
$clave = htmlspecialchars($p['Clave'] ?? '', ENT_QUOTES);
|
||||
|
||||
// Construir dirección
|
||||
$direccion = trim(implode(', ', array_filter([
|
||||
$p['Calles'] ?? '',
|
||||
'Num. Ext: ' . ($p['NumExt'] ?? ''),
|
||||
'Num. Int: ' . ($p['NumInt'] ?? ''),
|
||||
$p['Colonia'] ?? '',
|
||||
$p['Municipio'] ?? '',
|
||||
$p['Ciudad'] ?? '',
|
||||
'C.P. ' . ($p['CodigoPostal'] ?? ''),
|
||||
$p['EntidadFederativa'] ?? '',
|
||||
$p['Pais'] ?? ''
|
||||
])));
|
||||
// Construir dirección de forma más robusta
|
||||
$direccionParts = array_filter([
|
||||
$p['Calles'] ?? '',
|
||||
($p['NumExt'] ?? '') ? 'Num. Ext: ' . $p['NumExt'] : '',
|
||||
($p['NumInt'] ?? '') ? 'Num. Int: ' . $p['NumInt'] : '',
|
||||
$p['Colonia'] ?? '',
|
||||
$p['Municipio'] ?? '',
|
||||
$p['Ciudad'] ?? '',
|
||||
($p['CodigoPostal'] ?? '') ? 'C.P. ' . $p['CodigoPostal'] : '',
|
||||
$p['EntidadFederativa'] ?? '',
|
||||
$p['Pais'] ?? ''
|
||||
]);
|
||||
|
||||
$direccion = implode(', ', $direccionParts);
|
||||
|
||||
$dataList[] = [
|
||||
$clave,
|
||||
htmlspecialchars($p['Nombre'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['RFC'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['Ciudad'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['Telefono'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($direccion ?? '', ENT_QUOTES),
|
||||
// Acciones
|
||||
"<a href=\"/IMPORTADORES/proveedores/editar?clave=" . rawurlencode($clave) . "\" class=\"btn btn-sm btn-primary\">✏️</a>
|
||||
<button class=\"btn btn-sm btn-danger\" onclick=\"confirmDelete('{$clave}')\">🗑️</button>"
|
||||
];
|
||||
}
|
||||
} else {
|
||||
error_log('[ajax_lista] Respuesta inválida o status != 200');
|
||||
$dataList[] = [
|
||||
$clave,
|
||||
htmlspecialchars($p['Nombre'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['RFC'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['Ciudad'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['Telefono'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($direccion, ENT_QUOTES),
|
||||
"<a href=\"/IMPORTADORES/proveedores/editar?clave=" . rawurlencode($clave) . "\" class=\"btn btn-sm btn-primary\">✏️</a>
|
||||
<button class=\"btn btn-sm btn-danger\" onclick=\"confirmDelete('{$clave}')\">🗑️</button>"
|
||||
];
|
||||
}
|
||||
|
||||
// 6) Devolvemos siempre HTTP 200 con data (posiblemente vacío)
|
||||
@@ -161,20 +182,24 @@ function eliminar()
|
||||
exit;
|
||||
}
|
||||
|
||||
// CORRECCIÓN: Usar la misma URL base y corregir el Authorization header
|
||||
$url = rtrim($_ENV['API_URL'] ?? '', '/') . '/api/proveedores/' . urlencode($clave);
|
||||
error_log("[eliminar] DELETE $url");
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_CUSTOMREQUEST => 'DELETE',
|
||||
CURLOPT_HTTPHEADER => ["Authorization: $token",'Accept: application/json'],
|
||||
// CORRECCIÓN: Quitar el espacio extra y agregar Bearer
|
||||
CURLOPT_HTTPHEADER => ["Authorization: Bearer $token", 'Accept: application/json'],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
curl_exec($ch);
|
||||
$resp = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
error_log("[eliminar] HTTP $status: $resp");
|
||||
|
||||
header('Location: /IMPORTADORES/proveedores?deleted=' . ($status===200||$status===204 ? 'ok':'error'));
|
||||
exit;
|
||||
}
|
||||
@@ -203,16 +228,16 @@ function guardar()
|
||||
|
||||
// 2) Recoger datos del formulario
|
||||
$payload = [
|
||||
'Clave' => trim($_POST['Clave'] ?? ''),
|
||||
'Nombre' => trim($_POST['Nombre'] ?? ''),
|
||||
'RFC' => trim($_POST['RFC'] ?? ''),
|
||||
'Ciudad' => trim($_POST['Ciudad'] ?? ''),
|
||||
'Telefono' => trim($_POST['Telefono'] ?? ''),
|
||||
'Pais' => trim($_POST['Pais'] ?? ''),
|
||||
'Colonia' => trim($_POST['Colonia'] ?? ''),
|
||||
'Municipio' => trim($_POST['Municipio'] ?? ''),
|
||||
'CodigoPostal' => trim($_POST['CodigoPostal'] ?? ''),
|
||||
'EntidadFederativa' => trim($_POST['EntidadFederativa'] ?? ''),
|
||||
'Clave' => trim($_POST['Clave'] ?? ''),
|
||||
'Nombre' => trim($_POST['Nombre'] ?? ''),
|
||||
'RFC' => trim($_POST['RFC'] ?? ''),
|
||||
'Ciudad' => trim($_POST['Ciudad'] ?? ''),
|
||||
'Telefono' => trim($_POST['Telefono'] ?? ''),
|
||||
'Pais' => trim($_POST['Pais'] ?? ''),
|
||||
'Colonia' => trim($_POST['Colonia'] ?? ''),
|
||||
'Municipio' => trim($_POST['Municipio'] ?? ''),
|
||||
'CodigoPostal' => trim($_POST['CodigoPostal'] ?? ''),
|
||||
'EntidadFederativa' => trim($_POST['EntidadFederativa'] ?? ''),
|
||||
];
|
||||
|
||||
// 3) Validar campos obligatorios
|
||||
@@ -232,7 +257,7 @@ function guardar()
|
||||
|
||||
// 5) Llamada a la API para crear el proveedor
|
||||
$url = rtrim($_ENV['API_URL'] ?? '', '/') . '/api/proveedores';
|
||||
$ch = curl_init($url);
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
|
||||
@@ -73,7 +73,7 @@ function guardar()
|
||||
|
||||
$vehiculo = trim($_POST['vehiculo'] ?? '');
|
||||
$identFiscal = trim($_POST['identificador_fiscal'] ?? '');
|
||||
$idTrans = $_POST['id_transportista'] ?? null;
|
||||
$idTrans = $_POST['transportista_id'] ?? null;
|
||||
|
||||
if ($vehiculo === '' || $identFiscal === '' || !$idTrans) {
|
||||
die("❌ Todos los campos son obligatorios.");
|
||||
|
||||
@@ -40,7 +40,7 @@ function guardar()
|
||||
}
|
||||
|
||||
// Redirigir de vuelta a la lista o mostrar mensaje…
|
||||
header("Location: /IMPORTADORES/transportistas/lista?success=1");
|
||||
header("Location: /IMPORTADORES/transportistas/lista?created=ok");
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ function lista()
|
||||
include __DIR__ . '/../../views/transportistas/lista.php';
|
||||
}
|
||||
|
||||
/** Descarga la plantilla CSV para carga masiva **/
|
||||
/** Descarga la plantilla CSV para carga masiva **/
|
||||
function template()
|
||||
{
|
||||
$file = __DIR__ . '/../../public/downloads/transportistas_template.csv';
|
||||
|
||||
Reference in New Issue
Block a user