This commit is contained in:
2025-07-09 16:14:22 -06:00
parent 91b6806898
commit 287ad27274
39 changed files with 2517 additions and 2000 deletions

View File

@@ -3,30 +3,31 @@ require_once __DIR__ . '/../helpers/session.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../helpers/env.php';
function lista() {
function lista()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$usr = $_SESSION['usuario_id'];
$conn = getConnection();
$sql = "
SELECT
c.*,
(c.nombre + ' ' + c.apellido) AS nombre_completo,
(tr.clave_identificador + ' - ' + tr.nombre) AS transportista
FROM dbo.choferes c
JOIN dbo.transportistas tr
ON c.transportista_id = tr.id_transportista
WHERE tr.id_usuario = ?
AND c.status = 1
ORDER BY c.created_at DESC
";
$sql = "SELECT
c.*, (c.nombre + ' ' + c.apellido) AS nombre_completo, (tr.clave_identificador + ' - ' + tr.nombre) AS transportista
FROM dbo.choferes c
JOIN dbo.transportistas tr
ON c.transportista_id = tr.id_transportista
WHERE tr.id_usuario = ?
AND c.status = 1
ORDER BY c.created_at DESC
";
$stmt = sqlsrv_query($conn, $sql, [$usr]);
if ($stmt === false) {
die("Error en lista(): " . print_r(sqlsrv_errors(), true));
}
$choferes = [];
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$choferes[] = $r;
@@ -35,27 +36,33 @@ function lista() {
include __DIR__ . '/../../views/choferes/lista.php';
}
function crear() {
function crear()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$usr = $_SESSION['usuario_id'];
$conn = getConnection();
// OJO: aquí usamos "activo" según tu esquema original
$sql = "
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
";
$sql = "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
";
$stmt = sqlsrv_query($conn, $sql, [$usr]);
if ($stmt === false) {
die("Error en crear(): " . print_r(sqlsrv_errors(), true));
}
$transportistas = [];
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$transportistas[] = $r;
@@ -64,18 +71,20 @@ function crear() {
include __DIR__ . '/../../views/choferes/crear.php';
}
function guardar() {
function guardar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$transportista_id = $_POST['transportista_id'] ?? null;
$nombre = trim($_POST['nombre'] ?? '');
$apellido = trim($_POST['apellido'] ?? '');
$transportista_id = $_POST['transportista_id'] ?? null;
$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;
$gafete = trim($_POST['numero_gafete'] ?? '');
$telefono = trim($_POST['telefono'] ?? '');
$email = trim($_POST['email'] ?? '');
$fecha_ingreso = $_POST['fecha_ingreso'] ?: null;
if (!$transportista_id || !is_numeric($transportista_id) || $nombre === '' ||
$apellido === '' || $licencia === '' || $gafete === '') {
@@ -85,15 +94,17 @@ function guardar() {
$conn = getConnection();
// ✅ CRÍTICO: Verificar que el transportista pertenece al usuario
$sqlVerify = "SELECT id_transportista FROM dbo.transportistas WHERE id_transportista = ? AND id_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]);
$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.");
}
@@ -102,7 +113,7 @@ function guardar() {
$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));
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedTypes)) {
die("❌ Tipo de archivo no permitido. Solo JPG, PNG, GIF.");
@@ -125,24 +136,23 @@ function guardar() {
}
}
$sql = "
INSERT INTO dbo.choferes
(transportista_id, nombre, apellido, numero_licencia, numero_gafete, telefono, email, fecha_ingreso, foto_url, status)
VALUES (?, ?, ?, ?, ?, ?, ?, GETDATE(), ?, 1)
";
$sql = "INSERT INTO dbo.choferes
(transportista_id, nombre, apellido, numero_licencia, numero_gafete, telefono, email, fecha_ingreso, foto_url, status)
VALUES (?, ?, ?, ?, ?, ?, ?, GETDATE(), ?, 1)
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl
];
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl
];
$stmt = sqlsrv_query($conn, $sql, $params);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
$errors = sqlsrv_errors();
// ✅ Manejo específico de error de duplicado
@@ -158,32 +168,39 @@ function guardar() {
exit;
}
function editar() {
function editar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
die("❌ ID inválido.");
}
$conn = getConnection();
$sql = "
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
";
$sql = "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) {
die("Error en editar(): " . print_r(sqlsrv_errors(), true));
}
$chofer = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
if (!$chofer) {
die("❌ Chofer no encontrado o no autorizado.");
@@ -195,18 +212,22 @@ function editar() {
}
// Lista de transportistas
$sql2 = "
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
";
$sql2 = "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) {
die("Error en editar() [transportistas]: " . print_r(sqlsrv_errors(), true));
}
$transportistas = [];
while ($r = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$transportistas[] = $r;
@@ -216,14 +237,15 @@ function editar() {
}
/** Valida que el número de gafete sea único **/
function validarNumeroGafete() {
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'] ?? '');
$gafete = trim($_GET['numero_gafete'] ?? '');
$id_chofer = $_GET['id_chofer'] ?? null;
if ($gafete === '') {
@@ -235,11 +257,11 @@ function validarNumeroGafete() {
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";
$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";
$sql = "SELECT id_chofer FROM dbo.choferes WHERE numero_gafete = ? AND status = 1";
$stmt = sqlsrv_query($conn, $sql, [$gafete]);
}
@@ -252,21 +274,22 @@ function validarNumeroGafete() {
}
/** Procesa la actualización de un chofer **/
function actualizar() {
function actualizar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$id = $_POST['id_chofer'] ?? null;
$transportista_id = $_POST['transportista_id'] ?? null;
$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;
$status = isset($_POST['status']) ? 1 : 0;
$id = $_POST['id_chofer'] ?? null;
$transportista_id = $_POST['transportista_id'] ?? null;
$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;
$status = isset($_POST['status']) ? 1 : 0;
// Validación básica
if (
@@ -281,7 +304,8 @@ function actualizar() {
// ✅ 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]);
$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.");
}
@@ -290,7 +314,7 @@ function actualizar() {
$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));
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $allowedTypes)) {
die("❌ Tipo de archivo no permitido. Solo JPG, PNG, GIF.");
@@ -314,64 +338,62 @@ function actualizar() {
}
if ($fotoUrl) {
$sql = "
UPDATE dbo.choferes SET
transportista_id = ?,
nombre = ?,
apellido = ?,
numero_licencia = ?,
numero_gafete = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
foto_url = ?,
status = ?,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$sql = "UPDATE dbo.choferes SET
transportista_id = ?,
nombre = ?,
apellido = ?,
numero_licencia = ?,
numero_gafete = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
foto_url = ?,
status = ?,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl,
$status,
(int)$id
];
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$fotoUrl,
$status,
(int)$id
];
} else {
$sql = "
UPDATE dbo.choferes SET
transportista_id = ?,
nombre = ?,
apellido = ?,
numero_licencia = ?,
numero_gafete = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
status = ?,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$sql = "UPDATE dbo.choferes SET
transportista_id = ?,
nombre = ?,
apellido = ?,
numero_licencia = ?,
numero_gafete = ?,
telefono = ?,
email = ?,
fecha_ingreso = ?,
status = ?,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$params = [
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$status,
(int)$id
];
(int)$transportista_id,
$nombre,
$apellido,
$licencia,
$gafete,
$telefono,
$email,
$fecha_ingreso,
$status,
(int)$id
];
}
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
$errors = sqlsrv_errors();
// ✅ Manejo específico de error de duplicado
@@ -388,25 +410,28 @@ function actualizar() {
}
/** “Soft-delete” (status = 0) de un chofer **/
function eliminar() {
function eliminar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$id = $_GET['id'] ?? null;
if (!$id || !is_numeric($id)) {
die("❌ ID inválido.");
}
$conn = getConnection();
$sql = "
UPDATE dbo.choferes
SET status = 0,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$sql = "UPDATE dbo.choferes
SET status = 0,
updated_at = GETDATE()
WHERE id_chofer = ?
";
$stmt = sqlsrv_query($conn, $sql, [(int)$id]);
if ($stmt === false) {
die("❌ Error en eliminar(): " . print_r(sqlsrv_errors(), true));
}