Revisión 2.1

This commit is contained in:
2025-06-16 14:36:01 -06:00
parent c576ab5b3b
commit 4365919211
18 changed files with 601 additions and 290 deletions

View File

@@ -15,7 +15,7 @@ function lista() {
SELECT
c.*,
(c.nombre + ' ' + c.apellido) AS nombre_completo,
tr.nombre AS transportista
(tr.clave_identificador + ' - ' + tr.nombre) AS transportista
FROM dbo.choferes c
JOIN dbo.transportistas tr
ON c.transportista_id = tr.id_transportista
@@ -45,8 +45,10 @@ function crear() {
// OJO: aquí usamos "activo" según tu esquema original
$sql = "
SELECT id_transportista, nombre
FROM dbo.transportistas
SELECT t.id_transportista, t.clave_identificador, t.nombre, t.ciudad, t.domicilio,
c.nombre AS ciudad_nombre
FROM dbo.transportistas t
LEFT JOIN dbo.ciudades c ON t.ciudad = c.id_ciudad
WHERE id_usuario = ? AND activo = 1
ORDER BY nombre
";
@@ -70,44 +72,86 @@ function guardar() {
$nombre = trim($_POST['nombre'] ?? '');
$apellido = trim($_POST['apellido'] ?? '');
$licencia = trim($_POST['numero_licencia'] ?? '');
$gafete = trim($_POST['numero_gafete'] ?? '');
$telefono = trim($_POST['telefono'] ?? '');
$email = trim($_POST['email'] ?? '');
$fecha_ingreso = $_POST['fecha_ingreso'] ?: null;
if (!$transportista_id || $nombre === '' || $apellido === '' || $licencia === '') {
if (!$transportista_id || !is_numeric($transportista_id) || $nombre === '' ||
$apellido === '' || $licencia === '' || $gafete === '') {
die("❌ Todos los campos obligatorios deben llenarse.");
}
// Manejo de foto
$conn = getConnection();
// ✅ CRÍTICO: Verificar que el transportista pertenece al usuario
$sqlVerify = "SELECT id_transportista FROM dbo.transportistas WHERE id_transportista = ? AND id_usuario = ?";
$stmtVerify = sqlsrv_query($conn, $sqlVerify, [(int)$transportista_id, $_SESSION['usuario_id']]);
if (!$stmtVerify || !sqlsrv_fetch($stmtVerify)) {
die("❌ Transportista no autorizado.");
}
// ✅ CRÍTICO: Verificar que el número de gafete no existe
$sqlCheckGafete = "SELECT id_chofer FROM dbo.choferes WHERE numero_gafete = ? AND status = 1";
$stmtCheck = sqlsrv_query($conn, $sqlCheckGafete, [$gafete]);
if ($stmtCheck && sqlsrv_fetch($stmtCheck)) {
die("❌ El número de gafete '{$gafete}' ya está en uso. Por favor, use otro número.");
}
// ✅ MEJORADO: Manejo de foto con validación
$fotoUrl = null;
if (!empty($_FILES['foto']['tmp_name'])) {
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!empty($_FILES['foto']['tmp_name']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedTypes)) {
die("❌ Tipo de archivo no permitido. Solo JPG, PNG, GIF.");
}
// Validar tamaño (ej: máximo 5MB)
if ($_FILES['foto']['size'] > 5 * 1024 * 1024) {
die("❌ El archivo es demasiado grande. Máximo 5MB.");
}
$dest = __DIR__ . '/../../public/uploads/chofer_'.uniqid().".{$ext}";
if (!is_dir(dirname($dest))) mkdir(dirname($dest), 0755, true);
if (!is_dir(dirname($dest))) {
mkdir(dirname($dest), 0755, true);
}
if (move_uploaded_file($_FILES['foto']['tmp_name'], $dest)) {
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
} else {
error_log("Error al mover foto en guardar(): {$dest}");
die("❌ Error al subir la foto.");
}
}
$conn = getConnection();
$sql = "
INSERT INTO dbo.choferes
(transportista_id, nombre, apellido, numero_licencia, telefono, email, fecha_ingreso, foto_url, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1)
(transportista_id, nombre, apellido, numero_licencia, numero_gafete, telefono, email, fecha_ingreso, foto_url, status)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, GETDATE())
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl
];
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("Error en guardar(): " . print_r(sqlsrv_errors(), true));
$errors = sqlsrv_errors();
// ✅ Manejo específico de error de duplicado
foreach ($errors as $error) {
if (strpos($error['message'], 'UQ_numero_gafete') !== false) {
die("❌ El número de gafete ya está en uso. Por favor, use otro número.");
}
}
die("❌ Error en guardar(): " . print_r($errors, true));
}
header('Location: /IMPORTADORES/choferes/lista?created=ok');
@@ -126,13 +170,15 @@ function editar() {
$conn = getConnection();
$sql = "
SELECT c.*, tr.nombre AS transportista
FROM dbo.choferes c
JOIN dbo.transportistas tr
ON c.transportista_id = tr.id_transportista
WHERE c.id_chofer = ?
AND tr.id_usuario = ?
AND c.status = 1
SELECT
ch.*, tr.clave_identificador, tr.nombre AS transportista_nombre, tr.ciudad, tr.domicilio,
ciu.nombre AS ciudad_nombre
FROM dbo.choferes ch
LEFT JOIN dbo.transportistas tr ON ch.transportista_id = tr.id_transportista
LEFT JOIN dbo.ciudades ciu ON tr.ciudad = ciu.id_ciudad
WHERE ch.id_chofer = ?
AND tr.id_usuario = ?
AND ch.status = 1
";
$stmt = sqlsrv_query($conn, $sql, [(int)$id, $_SESSION['usuario_id']]);
if ($stmt === false) {
@@ -150,10 +196,12 @@ function editar() {
// Lista de transportistas
$sql2 = "
SELECT id_transportista, nombre
FROM dbo.transportistas
WHERE id_usuario = ? AND activo = 1
ORDER BY nombre
SELECT tr.id_transportista, tr.clave_identificador, tr.nombre, tr.domicilio,
ciu.nombre AS ciudad_nombre
FROM dbo.transportistas tr
LEFT JOIN dbo.ciudades ciu ON tr.ciudad = ciu.id_ciudad
WHERE tr.id_usuario = ? AND tr.activo = 1
ORDER BY tr.nombre
";
$stmt2 = sqlsrv_query($conn, $sql2, [$_SESSION['usuario_id']]);
if ($stmt2 === false) {
@@ -167,6 +215,42 @@ function editar() {
include __DIR__ . '/../../views/choferes/editar.php';
}
/** Valida que el número de gafete sea único **/
function validarNumeroGafete() {
if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'No autorizado']);
exit;
}
$gafete = trim($_GET['numero_gafete'] ?? '');
$id_chofer = $_GET['id_chofer'] ?? null;
if ($gafete === '') {
echo json_encode(['success' => false, 'message' => 'Número de gafete vacío']);
exit;
}
$conn = getConnection();
if ($id_chofer) {
// Edición: excluir el chofer actual
$sql = "SELECT id_chofer FROM dbo.choferes WHERE numero_gafete = ? AND id_chofer <> ? AND status = 1";
$stmt = sqlsrv_query($conn, $sql, [$gafete, $id_chofer]);
} else {
// Alta nueva
$sql = "SELECT id_chofer FROM dbo.choferes WHERE numero_gafete = ? AND status = 1";
$stmt = sqlsrv_query($conn, $sql, [$gafete]);
}
if ($stmt && sqlsrv_fetch($stmt)) {
echo json_encode(['success' => true, 'existe' => true]);
} else {
echo json_encode(['success' => true, 'existe' => false]);
}
exit;
}
/** Procesa la actualización de un chofer **/
function actualizar() {
if (!($_SESSION['usuario_id'] ?? false)) {
@@ -178,6 +262,7 @@ function actualizar() {
$nombre = trim($_POST['nombre'] ?? '');
$apellido = trim($_POST['apellido'] ?? '');
$licencia = trim($_POST['numero_licencia']?? '');
$gafete = trim($_POST['numero_gafete']?? '');
$telefono = trim($_POST['telefono'] ?? '');
$email = trim($_POST['email'] ?? '');
$fecha_ingreso = $_POST['fecha_ingreso'] ?: null;
@@ -187,15 +272,35 @@ function actualizar() {
if (
!$id || !is_numeric($id) ||
!$transportista_id || !is_numeric($transportista_id) ||
$nombre === '' || $apellido === '' || $licencia === ''
$nombre === '' || $apellido === '' || $licencia === '' || $gafete === ''
) {
die("❌ Datos inválidos o incompletos.");
}
// Manejo de foto nueva (opcional)
$conn = getConnection();
// ✅ CRÍTICO: Verificar que el número de gafete no existe (excluyendo el chofer actual)
$sqlCheckGafete = "SELECT id_chofer FROM dbo.choferes WHERE numero_gafete = ? AND id_chofer <> ? AND status = 1";
$stmtCheck = sqlsrv_query($conn, $sqlCheckGafete, [$gafete, $id_chofer]);
if ($stmtCheck && sqlsrv_fetch($stmtCheck)) {
die("❌ El número de gafete '{$gafete}' ya está en uso. Por favor, use otro número.");
}
// ✅ MEJORADO: Manejo de foto nueva con validación
$fotoUrl = null;
if (!empty($_FILES['foto']['tmp_name']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
$allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedTypes)) {
die("❌ Tipo de archivo no permitido. Solo JPG, PNG, GIF.");
}
// Validar tamaño (ej: máximo 5MB)
if ($_FILES['foto']['size'] > 5 * 1024 * 1024) {
die("❌ El archivo es demasiado grande. Máximo 5MB.");
}
$dest = __DIR__ . '/../../public/uploads/chofer_'.uniqid().".{$ext}";
if (!is_dir(dirname($dest))) {
mkdir(dirname($dest), 0755, true);
@@ -204,11 +309,10 @@ function actualizar() {
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
} else {
error_log("Error al mover foto en actualizar(): {$dest}");
die("❌ Error al subir la foto.");
}
}
$conn = getConnection();
if ($fotoUrl) {
$sql = "
UPDATE dbo.choferes SET
@@ -216,6 +320,7 @@ function actualizar() {
nombre = ?,
apellido = ?,
numero_licencia = ?,
numero_gafete = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
@@ -229,6 +334,7 @@ function actualizar() {
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
@@ -243,6 +349,7 @@ function actualizar() {
nombre = ?,
apellido = ?,
numero_licencia = ?,
numero_gafete = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
@@ -255,6 +362,7 @@ function actualizar() {
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
@@ -265,7 +373,14 @@ function actualizar() {
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("❌ Error en actualizar(): " . print_r(sqlsrv_errors(), true));
$errors = sqlsrv_errors();
// ✅ Manejo específico de error de duplicado
foreach ($errors as $error) {
if (strpos($error['message'], 'UQ_numero_gafete') !== false) {
die("❌ El número de gafete ya está en uso por otro chofer. Por favor, use otro número.");
}
}
die("❌ Error en actualizar(): " . print_r($errors, true));
}
header('Location: /IMPORTADORES/choferes/lista?updated=ok');

View File

@@ -14,7 +14,7 @@ function lista() {
// Sólo mostrar transportes de los transportistas que le pertenecen al usuario
$sql = "
SELECT t.*, tr.nombre AS transportista
SELECT t.*, (tr.clave_identificador + ' - ' + tr.nombre) AS transportista
FROM dbo.transportes t
JOIN dbo.transportistas tr
ON t.id_transportista = tr.id_transportista
@@ -41,8 +41,10 @@ function crear() {
// Traer transportistas propios para el select
$sql = "
SELECT id_transportista, clave_identificador, nombre
FROM dbo.transportistas
SELECT t.id_transportista, t.clave_identificador, t.nombre, t.ciudad, t.domicilio,
c.nombre AS ciudad_nombre
FROM dbo.transportistas t
LEFT JOIN dbo.ciudades c ON t.ciudad = c.id_ciudad
WHERE id_usuario = ? AND activo = 1
ORDER BY nombre
";
@@ -56,31 +58,62 @@ function crear() {
}
/** Procesa la creación de un nuevo transporte **/
function guardar() {
function guardar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$vehiculo = trim($_POST['vehiculo'] ?? '');
$identFiscal= trim($_POST['identificador_fiscal'] ?? '');
$idTrans = $_POST['id_transportista'] ?? null;
$vehiculo = trim($_POST['vehiculo'] ?? '');
$identFiscal = trim($_POST['identificador_fiscal'] ?? '');
$idTrans = $_POST['id_transportista'] ?? null;
if ($vehiculo === '' || $identFiscal === '' || !$idTrans) {
die("❌ Todos los campos son obligatorios.");
}
// Manejo de foto
// Validar que el transportista pertenece al usuario actual
$conn = getConnection();
$sqlCheck = "
SELECT 1 FROM dbo.transportistas
WHERE id_transportista = ? AND id_usuario = ? AND activo = 1
";
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$idTrans, $_SESSION['usuario_id']]);
if (!sqlsrv_fetch($stmtCheck)) {
die("❌ Transportista no válido o no autorizado.");
}
// Manejo de foto mejorado
$fotoUrl = null;
if (!empty($_FILES['foto']['tmp_name'])) {
$ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
$dest = __DIR__ . '/../../public/uploads/transporte_'.uniqid().".{$ext}";
if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExtensions)) {
die("❌ Formato de imagen no válido. Solo se permiten: " . implode(', ', $allowedExtensions));
}
// Validar tamaño (2MB max)
if ($_FILES['foto']['size'] > 2 * 1024 * 1024) {
die("❌ La imagen no debe exceder 2 MB.");
}
$uploadDir = __DIR__ . '/../../public/uploads/';
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
$dest = $uploadDir . 'transporte_' . uniqid() . ".{$ext}";
if (move_uploaded_file($_FILES['foto']['tmp_name'], $dest)) {
// ruta relativa
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
} else {
error_log("Error al mover archivo en guardar(): {$dest}");
die("❌ Error al subir la imagen.");
}
}
$conn = getConnection();
// Insertar el nuevo transporte
$sql = "
INSERT INTO dbo.transportes
(vehiculo, identificador_fiscal, foto_url, status, id_transportista)
@@ -88,8 +121,17 @@ function guardar() {
";
$params = [$vehiculo, $identFiscal, $fotoUrl, $idTrans];
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("❌ Error al guardar: ".print_r(sqlsrv_errors(),true));
$errors = sqlsrv_errors();
error_log("Error SQL en guardar transporte: " . print_r($errors, true));
die("❌ Error al guardar: " . $errors[0]['message']);
}
// Verificar que se insertó correctamente
$rowsAffected = sqlsrv_rows_affected($stmt);
if ($rowsAffected === 0) {
die("❌ No se pudo crear el registro.");
}
header('Location: /IMPORTADORES/transportes/lista?created=ok');
@@ -124,8 +166,10 @@ function editar() {
// Mismo select de transportistas que en crear()
$sql2 = "
SELECT id_transportista, nombre
FROM dbo.transportistas
SELECT t.id_transportista, t.clave_identificador, t.nombre, t.ciudad, t.domicilio,
c.nombre AS ciudad_nombre
FROM dbo.transportistas t
LEFT JOIN dbo.ciudades c ON t.ciudad = c.id_ciudad
WHERE id_usuario = ? AND activo = 1
ORDER BY nombre
";
@@ -145,24 +189,49 @@ function actualizar() {
$vehiculo = trim($_POST['vehiculo'] ?? '');
$identFiscal = trim($_POST['identificador_fiscal'] ?? '');
$idTrans = $_POST['id_transportista'] ?? null;
if (!$id || !is_numeric($id) || $vehiculo === '' || $identFiscal === '' || !$idTrans) {
die("❌ Faltan datos.");
}
$conn = getConnection();
// Antes del UPDATE, validar que el transporte pertenece al usuario
$sqlCheck = "
SELECT 1 FROM dbo.transportes t
JOIN dbo.transportistas tr ON t.id_transportista = tr.id_transportista
wHERE t.id_transporte = ? AND tr.id_usuario = ?
";
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$id, $_SESSION['usuario_id']]);
if ($stmtCheck === false) {
$errors = sqlsrv_errors();
error_log("Error SQL al validar transporte: " . print_r($errors, true));
die("❌ Error en la validación SQL.");
}
if (!sqlsrv_fetch($stmtCheck)) {
die("❌ No autorizado para modificar este transporte.");
}
// —– Manejo de nueva foto —–
$fotoUrl = null;
if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
$allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedExtensions)) {
die("❌ Formato de imagen no válido.");
}
$dest = __DIR__ . '/../../public/uploads/transporte_'.uniqid().".{$ext}";
if (!is_dir(dirname($dest))) {
mkdir(dirname($dest), 0755, true);
}
if (move_uploaded_file($_FILES['foto']['tmp_name'], $dest)) {
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
} else {
error_log("Error al mover archivo en actualizar(): {$dest}");
die("❌ Error al subir la imagen.");
}
}
@@ -174,7 +243,7 @@ function actualizar() {
identificador_fiscal = ?,
id_transportista = ?,
foto_url = ?
WHERE id_transporte = ?
WHERE id_transporte = ?
";
$params = [$vehiculo, $identFiscal, $idTrans, $fotoUrl, $id];
} else {
@@ -190,7 +259,15 @@ function actualizar() {
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("❌ Error al actualizar: " . print_r(sqlsrv_errors(), true));
$errors = sqlsrv_errors();
error_log("Error SQL en actualizar transporte: " . print_r($errors, true));
die("❌ Error al actualizar: " . $errors[0]['message']);
}
// Verificar si se afectó alguna fila
$rowsAffected = sqlsrv_rows_affected($stmt);
if ($rowsAffected === 0) {
die("❌ No se pudo actualizar el registro.");
}
header('Location: /IMPORTADORES/transportes/lista?updated=ok');

View File

@@ -2,6 +2,7 @@
require_once __DIR__ . '/../helpers/session.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../helpers/env.php';
ob_clean();
function guardar() {
if (!($_SESSION['usuario_id'] ?? false)) {
@@ -264,21 +265,13 @@ function ajax_lista() {
$params = [$usr];
if ($search !== '') {
// Ahora buscamos en campos de transportista Y en el nombre de la ciudad
$where .= " AND (
t.clave_identificador LIKE ? OR
t.nombre LIKE ? OR
t.rfc LIKE ? OR
t.curp LIKE ? OR
t.telefono LIKE ? OR
t.caat LIKE ? OR
c.nombre LIKE ? OR
p.nombre LIKE ? OR
e.nombre LIKE ?
c.nombre LIKE ?
)";
$like = "%{$search}%";
// Agregamos el parámetro para cada campo de búsqueda
$params = array_merge($params, array_fill(0, 9, $like));
$params = array_merge($params, array_fill(0, 3, $like));
}
// 5) Total registros filtrados (CON JOIN)
@@ -332,13 +325,23 @@ function ajax_lista() {
}
// 7) Devolver JSON
$response = [
"draw" => $draw,
"recordsTotal" => $recordsTotal,
"recordsFiltered" => $recordsFiltered,
"data" => $data
];
$json = json_encode($response, JSON_UNESCAPED_UNICODE);
if (json_last_error() !== JSON_ERROR_NONE) {
http_response_code(500);
echo json_encode(["error" => "JSON encoding error: " . json_last_error_msg()]);
exit;
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode([
"draw" => $draw,
"recordsTotal" => $recordsTotal,
"recordsFiltered" => $recordsFiltered,
"data" => $data
]);
header('Cache-Control: no-cache, must-revalidate');
echo $json;
exit;
}