main
inicio
This commit is contained in:
319
app/controllers/transportes.php
Normal file
319
app/controllers/transportes.php
Normal file
@@ -0,0 +1,319 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once __DIR__ . '/../../config/database.php';
|
||||
|
||||
/**
|
||||
* Listado de transportes (sólo activos) para el importador logueado
|
||||
*/
|
||||
function lista() {
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
$usr = $_SESSION['usuario_id'];
|
||||
$conn = getConnection();
|
||||
|
||||
// Sólo mostrar transportes de los transportistas que le pertenecen al usuario
|
||||
$sql = "
|
||||
SELECT t.*, tr.nombre AS transportista
|
||||
FROM dbo.transportes t
|
||||
JOIN dbo.transportistas tr
|
||||
ON t.id_transportista = tr.id_transportista
|
||||
WHERE tr.id_usuario = ? AND t.status = 1
|
||||
ORDER BY t.creado_en DESC
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$usr]);
|
||||
$transportes = [];
|
||||
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$transportes[] = $r;
|
||||
}
|
||||
|
||||
include __DIR__ . '/../../views/transportes/lista.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Formulario de alta de transporte
|
||||
*/
|
||||
function crear() {
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
$usr = $_SESSION['usuario_id'];
|
||||
$conn = getConnection();
|
||||
|
||||
// Traer transportistas propios para el select
|
||||
$sql = "
|
||||
SELECT id_transportista, nombre
|
||||
FROM dbo.transportistas
|
||||
WHERE id_usuario = ? AND activo = 1
|
||||
ORDER BY nombre
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$usr]);
|
||||
$transportistas = [];
|
||||
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
|
||||
$transportistas[] = $r;
|
||||
}
|
||||
|
||||
include __DIR__ . '/../../views/transportes/crear.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Procesa la creación de un nuevo transporte
|
||||
*/
|
||||
function guardar() {
|
||||
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
die("⚠️ No autorizado.");
|
||||
}
|
||||
$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
|
||||
$fotoUrl = null;
|
||||
if (!empty($_FILES['foto']['tmp_name'])) {
|
||||
$ext = pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION);
|
||||
$dest = __DIR__ . '/../../public/uploads/transporte_'.uniqid().".{$ext}";
|
||||
if (move_uploaded_file($_FILES['foto']['tmp_name'], $dest)) {
|
||||
// ruta relativa
|
||||
$fotoUrl = "/IMPORTADORES/public/uploads/" . basename($dest);
|
||||
}
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "
|
||||
INSERT INTO dbo.transportes
|
||||
(vehiculo, identificador_fiscal, foto_url, status, id_transportista)
|
||||
VALUES (?, ?, ?, 1, ?)
|
||||
";
|
||||
$params = [$vehiculo, $identFiscal, $fotoUrl, $idTrans];
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
if ($stmt === false) {
|
||||
die("❌ Error al guardar: ".print_r(sqlsrv_errors(),true));
|
||||
}
|
||||
|
||||
header('Location: /IMPORTADORES/transportes/lista?created=ok');
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formulario de edición
|
||||
*/
|
||||
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();
|
||||
// Validar pertenencia igual que en index()
|
||||
$sql = "
|
||||
SELECT t.*, tr.nombre AS transportista
|
||||
FROM dbo.transportes t
|
||||
JOIN dbo.transportistas tr
|
||||
ON t.id_transportista = tr.id_transportista
|
||||
WHERE t.id_transporte = ?
|
||||
AND tr.id_usuario = ?
|
||||
AND t.status = 1
|
||||
";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$id, $_SESSION['usuario_id']]);
|
||||
$t = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||
if (!$t) die("❌ Transporte no encontrado o no autorizado.");
|
||||
|
||||
// Mismo select de transportistas que en crear()
|
||||
$sql2 = "
|
||||
SELECT id_transportista, nombre
|
||||
FROM dbo.transportistas
|
||||
WHERE id_usuario = ? AND activo = 1
|
||||
ORDER BY nombre
|
||||
";
|
||||
$stmt2 = sqlsrv_query($conn, $sql2, [$_SESSION['usuario_id']]);
|
||||
$transportistas = [];
|
||||
while ($r=sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC)) $transportistas[]=$r;
|
||||
|
||||
include __DIR__ . '/../../views/transportes/editar.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Procesa la actualización
|
||||
*/
|
||||
function actualizar() {
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
die("⚠️ No autorizado.");
|
||||
}
|
||||
$id = $_POST['id_transporte'] ?? null;
|
||||
$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();
|
||||
|
||||
// —– Manejo de nueva foto —–
|
||||
$fotoUrl = null;
|
||||
if (isset($_FILES['foto']) && $_FILES['foto']['error'] === UPLOAD_ERR_OK) {
|
||||
$ext = strtolower(pathinfo($_FILES['foto']['name'], PATHINFO_EXTENSION));
|
||||
$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}");
|
||||
}
|
||||
}
|
||||
|
||||
// —– Construye el UPDATE dinámico —–
|
||||
if ($fotoUrl) {
|
||||
$sql = "
|
||||
UPDATE dbo.transportes SET
|
||||
vehiculo = ?,
|
||||
identificador_fiscal = ?,
|
||||
id_transportista = ?,
|
||||
foto_url = ?
|
||||
WHERE id_transporte = ?
|
||||
";
|
||||
$params = [$vehiculo, $identFiscal, $idTrans, $fotoUrl, $id];
|
||||
} else {
|
||||
$sql = "
|
||||
UPDATE dbo.transportes SET
|
||||
vehiculo = ?,
|
||||
identificador_fiscal = ?,
|
||||
id_transportista = ?
|
||||
WHERE id_transporte = ?
|
||||
";
|
||||
$params = [$vehiculo, $identFiscal, $idTrans, $id];
|
||||
}
|
||||
|
||||
$stmt = sqlsrv_query($conn, $sql, $params);
|
||||
if ($stmt === false) {
|
||||
die("❌ Error al actualizar: " . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
header('Location: /IMPORTADORES/transportes/lista?updated=ok');
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* “Soft-delete” (status = 0)
|
||||
*/
|
||||
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.transportes SET status = 0 WHERE id_transporte = ?";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$id]);
|
||||
if ($stmt === false) {
|
||||
die("❌ Error al eliminar: ".print_r(sqlsrv_errors(),true));
|
||||
}
|
||||
header('Location: /IMPORTADORES/transportes/lista?deleted=ok');
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Formulario de importación masiva
|
||||
*/
|
||||
function masivo() {
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
header('Location: /IMPORTADORES/login');
|
||||
exit;
|
||||
}
|
||||
include __DIR__ . '/../../views/transportes/importar_masivo.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Procesa la importación masiva desde CSV
|
||||
*/
|
||||
function importarGuardar() {
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
die("⚠️ No autorizado.");
|
||||
}
|
||||
|
||||
// Validar subida del archivo
|
||||
if (!isset($_FILES['csv']) || $_FILES['csv']['error'] !== UPLOAD_ERR_OK) {
|
||||
$_SESSION['import_result'] = [
|
||||
'imported' => 0,
|
||||
'errors' => ["Error al subir el archivo CSV."]
|
||||
];
|
||||
header('Location: /IMPORTADORES/transportes/importar');
|
||||
exit;
|
||||
}
|
||||
|
||||
$tmp = $_FILES['csv']['tmp_name'];
|
||||
$handle = fopen($tmp, 'r');
|
||||
$headers = fgetcsv($handle, 1000, ',');
|
||||
$conn = getConnection();
|
||||
$usr = $_SESSION['usuario_id'];
|
||||
$imported = 0;
|
||||
$errors = [];
|
||||
$row = 1;
|
||||
|
||||
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
|
||||
$row++;
|
||||
if (count($data) < 3) {
|
||||
$errors[] = "Fila $row: formato incorrecto.";
|
||||
continue;
|
||||
}
|
||||
list($vehiculo, $identFiscal, $idTrans) = array_map('trim', $data);
|
||||
|
||||
// Validaciones básicas
|
||||
if ($vehiculo === '' || $identFiscal === '' || !is_numeric($idTrans)) {
|
||||
$errors[] = "Fila $row: datos incompletos o inválidos.";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Verificar que el transportista pertenezca al usuario
|
||||
$sqlCheck = "SELECT COUNT(*) AS cnt
|
||||
FROM dbo.transportistas
|
||||
WHERE id_transportista = ? AND id_usuario = ?";
|
||||
$stmtCheck = sqlsrv_query($conn, $sqlCheck, [$idTrans, $usr]);
|
||||
$rCheck = sqlsrv_fetch_array($stmtCheck, SQLSRV_FETCH_ASSOC);
|
||||
if ($rCheck['cnt'] == 0) {
|
||||
$errors[] = "Fila $row: transportista $idTrans no válido.";
|
||||
continue;
|
||||
}
|
||||
|
||||
// Insertar sin foto
|
||||
$sql = "INSERT INTO dbo.transportes
|
||||
(vehiculo, identificador_fiscal, foto_url, status, id_transportista)
|
||||
VALUES (?, ?, NULL, 1, ?)";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$vehiculo, $identFiscal, $idTrans]);
|
||||
if ($stmt === false) {
|
||||
$errors[] = "Fila $row: error al insertar.";
|
||||
continue;
|
||||
}
|
||||
$imported++;
|
||||
}
|
||||
|
||||
fclose($handle);
|
||||
|
||||
// Guardar resultado en sesión y redirigir de vuelta al formulario
|
||||
$_SESSION['import_result'] = [
|
||||
'imported' => $imported,
|
||||
'errors' => $errors
|
||||
];
|
||||
header('Location: /IMPORTADORES/transportes/masivo');
|
||||
exit;
|
||||
}
|
||||
Reference in New Issue
Block a user