Files
MVE/app/controllers/catalogo_pedimentos.php

687 lines
22 KiB
PHP

<?php
require_once __DIR__ . '/../helpers/session.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../helpers/crypto.php';
function index()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
include __DIR__ . '/../../views/catalogo_pedimentos/index.php';
}
function lista()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
include __DIR__ . '/../../views/catalogo_pedimentos/lista.php';
}
function crear()
{
if (!($_SESSION['usuario_id'] ?? false)) {
header('Location: /IMPORTADORES/login');
exit;
}
$conn = getConnection();
$id_usuario = $_SESSION['usuario_id'];
// Obtener información del importador
$sqlImportador = "SELECT rfc, nombre, correo FROM informacion_general WHERE id_usuario = ?";
$stmtImportador = sqlsrv_query($conn, $sqlImportador, [$id_usuario]);
if ($stmtImportador === false) {
die("❌ Error al consultar información del importador: " . print_r(sqlsrv_errors(), true));
}
$importador = sqlsrv_fetch_array($stmtImportador, SQLSRV_FETCH_ASSOC);
// Obtener claves de pedimentos activas del usuario
$sqlClaves = "SELECT codigo, descripcion FROM claves_pedimentos_usuario
WHERE id_usuario = ? AND activo = 1 AND tipo_operacion = 'importacion'
ORDER BY codigo ASC";
$stmtClaves = sqlsrv_query($conn, $sqlClaves, [$id_usuario]);
$claves_pedimentos = [];
if ($stmtClaves !== false) {
while ($row = sqlsrv_fetch_array($stmtClaves, SQLSRV_FETCH_ASSOC)) {
$claves_pedimentos[] = $row;
}
}
include __DIR__ . '/../../views/catalogo_pedimentos/crear.php';
}
function guardar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$conn = getConnection();
$id_usuario = $_SESSION['usuario_id'];
// Obtener información del importador automáticamente
$sqlImportador = "SELECT rfc, nombre FROM informacion_general WHERE id_usuario = ?";
$stmtImportador = sqlsrv_query($conn, $sqlImportador, [$id_usuario]);
if ($stmtImportador === false) {
die("❌ Error al consultar información del importador: " . print_r(sqlsrv_errors(), true));
}
$importador = sqlsrv_fetch_array($stmtImportador, SQLSRV_FETCH_ASSOC);
if (!$importador) {
die("❌ Error: No se encontró información del importador. Configure su información general primero.");
}
// Obtener datos del formulario
$pedimento = trim($_POST['pedimento'] ?? '');
$clave_ped = trim($_POST['clave_ped'] ?? '');
$tipo_operacion = $_POST['tipo_operacion'] ?? 1; // Por defecto importación
$tipo_pedimento = $_POST['tipo_pedimento'] ?? 1; // Por defecto normal
$regimen = trim($_POST['regimen'] ?? '');
$destino = trim($_POST['destino'] ?? '');
// Fechas
$fecha_pedimento = $_POST['fecha_pedimento'] ?? null;
$fecha_inicio = $_POST['fecha_inicio'] ?? null;
$fecha_final = $_POST['fecha_final'] ?? null;
// Información adicional
$archivo_final_previo = trim($_POST['archivo_final_previo'] ?? '');
$acuse_cons = trim($_POST['acuse_cons'] ?? '');
$tipo = trim($_POST['tipo'] ?? '');
$status = isset($_POST['status']) ? (int)$_POST['status'] : 1;
// Validaciones
if (empty($pedimento)) {
die("❌ El número de pedimento es obligatorio.");
}
if (empty($clave_ped)) {
die("❌ La clave de pedimento es obligatoria.");
}
// Convertir fechas a formato YYYYMMDD si están presentes
$fecha_pedimento_int = null;
$fecha_inicio_int = null;
$fecha_final_int = null;
if ($fecha_pedimento) {
$fecha_pedimento_int = (int)str_replace('-', '', $fecha_pedimento);
}
if ($fecha_inicio) {
$fecha_inicio_int = (int)str_replace('-', '', $fecha_inicio);
}
if ($fecha_final) {
$fecha_final_int = (int)str_replace('-', '', $fecha_final);
}
$sql = "INSERT INTO PREVIOS_COMPARTIDOS_WS
(Pedimento, ClienteRFC, ClienteNombre, ClavePed, TipoOperacion, TipoPedimento,
Regimen, Destino, FechaPedimento, FechaInicio, FechaFinal,
ArchivoFinalPrevio, AcuseCons, Tipo, Status, Timestamp, id_usuario)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, GETDATE(), ?)";
$params = [
$pedimento,
$importador['rfc'],
$importador['nombre'],
$clave_ped,
$tipo_operacion,
$tipo_pedimento,
$regimen,
$destino,
$fecha_pedimento_int,
$fecha_inicio_int,
$fecha_final_int,
$archivo_final_previo,
$acuse_cons,
$tipo,
$status,
$id_usuario
];
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("❌ Error al guardar: " . print_r(sqlsrv_errors(), true));
}
header('Location: /IMPORTADORES/catalogo_pedimentos/lista?created=ok');
exit;
}
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();
$id_usuario = $_SESSION['usuario_id'];
// Obtener información del importador
$sqlImportador = "SELECT rfc, nombre FROM informacion_general WHERE id_usuario = ?";
$stmtImportador = sqlsrv_query($conn, $sqlImportador, [$id_usuario]);
if ($stmtImportador === false) {
die("❌ Error al consultar información del importador: " . print_r(sqlsrv_errors(), true));
}
$importador = sqlsrv_fetch_array($stmtImportador, SQLSRV_FETCH_ASSOC);
// Obtener claves de pedimentos activas del usuario
$sqlClaves = "SELECT codigo, descripcion FROM claves_pedimentos_usuario
WHERE id_usuario = ? AND activo = 1 AND tipo_operacion = 'importacion'
ORDER BY codigo ASC";
$stmtClaves = sqlsrv_query($conn, $sqlClaves, [$id_usuario]);
$claves_pedimentos = [];
if ($stmtClaves !== false) {
while ($row = sqlsrv_fetch_array($stmtClaves, SQLSRV_FETCH_ASSOC)) {
$claves_pedimentos[] = $row;
}
}
// Obtener datos del pedimento
$sql = "SELECT * FROM PREVIOS_COMPARTIDOS_WS WHERE IdPrevio = ?";
$stmt = sqlsrv_query($conn, $sql, [$id]);
if ($stmt === false) {
die("❌ Error en consulta: " . print_r(sqlsrv_errors(), true));
}
$previo = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
if (!$previo) {
die("❌ Pedimento no encontrado.");
}
include __DIR__ . '/../../views/catalogo_pedimentos/editar.php';
}
function actualizar()
{
if (!($_SESSION['usuario_id'] ?? false)) {
die("⚠️ No autorizado.");
}
$conn = getConnection();
$id_usuario = $_SESSION['usuario_id'];
// Obtener información del importador automáticamente
$sqlImportador = "SELECT rfc, nombre FROM informacion_general WHERE id_usuario = ?";
$stmtImportador = sqlsrv_query($conn, $sqlImportador, [$id_usuario]);
if ($stmtImportador === false) {
die("❌ Error al consultar información del importador: " . print_r(sqlsrv_errors(), true));
}
$importador = sqlsrv_fetch_array($stmtImportador, SQLSRV_FETCH_ASSOC);
if (!$importador) {
die("❌ Error: No se encontró información del importador.");
}
$id_previo = $_POST['id_previo'] ?? null;
$pedimento = trim($_POST['pedimento'] ?? '');
$clave_ped = trim($_POST['clave_ped'] ?? '');
$tipo_operacion = $_POST['tipo_operacion'] ?? 1;
$tipo_pedimento = $_POST['tipo_pedimento'] ?? 1;
$regimen = trim($_POST['regimen'] ?? '');
$destino = trim($_POST['destino'] ?? '');
// Fechas
$fecha_pedimento = $_POST['fecha_pedimento'] ?? null;
$fecha_inicio = $_POST['fecha_inicio'] ?? null;
$fecha_final = $_POST['fecha_final'] ?? null;
// Información adicional
$archivo_final_previo = trim($_POST['archivo_final_previo'] ?? '');
$acuse_cons = trim($_POST['acuse_cons'] ?? '');
$tipo = trim($_POST['tipo'] ?? '');
$status = isset($_POST['status']) ? (int)$_POST['status'] : 1;
if (!$id_previo || !is_numeric($id_previo)) {
die("❌ ID inválido.");
}
// Validaciones
if (empty($pedimento)) {
die("❌ El número de pedimento es obligatorio.");
}
if (empty($clave_ped)) {
die("❌ La clave de pedimento es obligatoria.");
}
// Convertir fechas a formato YYYYMMDD si están presentes
$fecha_pedimento_int = null;
$fecha_inicio_int = null;
$fecha_final_int = null;
if ($fecha_pedimento) {
$fecha_pedimento_int = (int)str_replace('-', '', $fecha_pedimento);
}
if ($fecha_inicio) {
$fecha_inicio_int = (int)str_replace('-', '', $fecha_inicio);
}
if ($fecha_final) {
$fecha_final_int = (int)str_replace('-', '', $fecha_final);
}
$sql = "UPDATE PREVIOS_COMPARTIDOS_WS SET
Pedimento = ?, ClienteRFC = ?, ClienteNombre = ?, ClavePed = ?,
TipoOperacion = ?, TipoPedimento = ?, Regimen = ?, Destino = ?,
FechaPedimento = ?, FechaInicio = ?, FechaFinal = ?,
ArchivoFinalPrevio = ?, AcuseCons = ?, Tipo = ?, Status = ?
WHERE IdPrevio = ?";
$params = [
$pedimento,
$importador['rfc'],
$importador['nombre'],
$clave_ped,
$tipo_operacion,
$tipo_pedimento,
$regimen,
$destino,
$fecha_pedimento_int,
$fecha_inicio_int,
$fecha_final_int,
$archivo_final_previo,
$acuse_cons,
$tipo,
$status,
$id_previo
];
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false) {
die("❌ Error al actualizar: " . print_r(sqlsrv_errors(), true));
}
header('Location: /IMPORTADORES/catalogo_pedimentos/lista?updated=ok');
exit;
}
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 = "DELETE FROM PREVIOS_COMPARTIDOS_WS WHERE IdPrevio = ?";
$stmt = sqlsrv_query($conn, $sql, [$id]);
if ($stmt === false) {
die("❌ Error al eliminar: " . print_r(sqlsrv_errors(), true));
}
header('Location: /IMPORTADORES/catalogo_pedimentos/lista?deleted=ok');
exit;
}
function ajax_lista()
{
if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(403);
echo json_encode([]);
exit;
}
$id_usuario = $_SESSION['usuario_id'];
$conn = getConnection();
// Parámetros de DataTables
$draw = intval($_GET['draw'] ?? 0);
$start = intval($_GET['start'] ?? 0);
$length = intval($_GET['length'] ?? 10);
$search = $_GET['search']['value'] ?? '';
// Total registros sin filtro en nuevas tablas
$sqlTotal = "SELECT COUNT(*) AS total FROM pedimentos WHERE usuario_id = ?";
$stmtTotal = sqlsrv_query($conn, $sqlTotal, [$id_usuario]);
if ($stmtTotal === false) {
echo json_encode([
"draw" => $draw,
"recordsTotal" => 0,
"recordsFiltered" => 0,
"data" => [],
"error" => "Error al contar registros totales"
]);
exit;
}
$rowT = sqlsrv_fetch_array($stmtTotal, SQLSRV_FETCH_ASSOC);
$recordsTotal = (int)($rowT['total'] ?? 0);
// Filtro y búsqueda
$where = "p.usuario_id = ?";
$params = [$id_usuario];
if ($search !== '') {
$where .= " AND (p.numero_pedimento LIKE ? OR p.rfc_importador LIKE ? OR p.clave_documento LIKE ? OR p.patente LIKE ? OR p.aduana LIKE ?)";
$like = "%{$search}%";
$params = array_merge($params, [$like, $like, $like, $like, $like]);
}
// Total filtrado
$sqlFiltered = "SELECT COUNT(*) AS total FROM pedimentos p WHERE $where";
$stmtF = sqlsrv_query($conn, $sqlFiltered, $params);
if ($stmtF === false) {
echo json_encode([
"draw" => $draw,
"recordsTotal" => $recordsTotal,
"recordsFiltered" => 0,
"data" => [],
"error" => "Error al contar registros filtrados"
]);
exit;
}
$rowF = sqlsrv_fetch_array($stmtF, SQLSRV_FETCH_ASSOC);
$recordsFiltered = (int)($rowF['total'] ?? 0);
// Datos paginados
$sqlData = "SELECT p.id, p.numero_pedimento, p.rfc_importador, p.fecha_creacion, p.estado,
ig.nombre AS nombre_importador
FROM pedimentos p
LEFT JOIN informacion_general ig ON ig.id_usuario = p.usuario_id
WHERE $where
ORDER BY p.fecha_creacion DESC
OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
$paramsData = array_merge($params, [$start, $length]);
$stmtD = sqlsrv_query($conn, $sqlData, $paramsData);
$data = [];
if ($stmtD !== false) {
while ($r = sqlsrv_fetch_array($stmtD, SQLSRV_FETCH_ASSOC)) {
$fecha = '';
if (isset($r['fecha_creacion'])) {
if ($r['fecha_creacion'] instanceof DateTime) {
$fecha = $r['fecha_creacion']->format('Y-m-d H:i:s');
} elseif (is_array($r['fecha_creacion']) && isset($r['fecha_creacion']['date'])) {
// Por si viene como array (SQLSRV con print_r)
$fecha = substr($r['fecha_creacion']['date'], 0, 19);
}
}
$estado = strtolower((string)$r['estado']) === 'activo' || $r['estado'] === 1 ? 'Activo' : 'Inactivo';
$data[] = [
$r['id'],
$r['numero_pedimento'],
$r['rfc_importador'],
$r['nombre_importador'] ?? '',
$fecha,
$estado
];
}
}
$response = [
"draw" => $draw,
"recordsTotal" => $recordsTotal,
"recordsFiltered" => $recordsFiltered,
"data" => $data
];
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit;
}
function buscar_pedimentos()
{
if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(403);
echo json_encode([]);
exit;
}
$id_usuario = $_SESSION['usuario_id'];
$query = trim($_GET['q'] ?? '');
$limit = intval($_GET['limit'] ?? 10); // ✅ NUEVO: Parámetro limit con valor por defecto
// ✅ MODIFICADO: Para el panel de referencia, si no hay query, traer los más recientes
if (empty($query)) {
// Si no hay query, obtener los pedimentos más recientes para el panel de referencia
$whereCondition = "ClienteRFC = ? AND Status = 1";
$searchParams = [];
} else {
// Si hay query, mantener la lógica original de búsqueda
if (strlen($query) < 3) {
echo json_encode([]);
exit;
}
$whereCondition = "ClienteRFC = ? AND (Pedimento LIKE ? OR ClienteNombre LIKE ? OR ClavePed LIKE ?) AND Status = 1";
$like = "%{$query}%";
$searchParams = [$like, $like, $like];
}
$conn = getConnection();
// Obtener RFC del usuario para filtrar solo sus pedimentos
$sqlImportador = "SELECT rfc FROM informacion_general WHERE id_usuario = ?";
$stmtImportador = sqlsrv_query($conn, $sqlImportador, [$id_usuario]);
if ($stmtImportador === false) {
echo json_encode([]);
exit;
}
$importador = sqlsrv_fetch_array($stmtImportador, SQLSRV_FETCH_ASSOC);
if (!$importador) {
echo json_encode([]);
exit;
}
// ✅ MODIFICADO: Query dinámico con límite configurable
$sql = "SELECT TOP {$limit} IdPrevio, Pedimento, ClienteRFC, ClienteNombre, ClavePed, Timestamp
FROM PREVIOS_COMPARTIDOS_WS
WHERE {$whereCondition}
ORDER BY Timestamp DESC";
$params = array_merge([$importador['rfc']], $searchParams);
$stmt = sqlsrv_query($conn, $sql, $params);
$pedimentos = [];
if ($stmt !== false) {
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$fecha_formateada = '';
if ($row['Timestamp'] instanceof DateTime) {
$fecha_formateada = $row['Timestamp']->format('d/m/Y');
}
$pedimentos[] = [
'IdPrevio' => $row['IdPrevio'],
'Pedimento' => $row['Pedimento'],
'ClienteRFC' => $row['ClienteRFC'],
'ClienteNombre' => $row['ClienteNombre'],
'ClavePed' => $row['ClavePed'],
'fecha_formateada' => $fecha_formateada
];
}
}
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($pedimentos, JSON_UNESCAPED_UNICODE);
exit;
}
/**
* Devuelve información general del pedimento (cabecera)
* GET /IMPORTADORES/catalogo_pedimentos/ajax_pedimento?id=123
*/
function ajax_pedimento()
{
if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'No autorizado']);
exit;
}
$id_usuario = $_SESSION['usuario_id'];
$pedimento_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($pedimento_id <= 0) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'ID inválido']);
exit;
}
$conn = getConnection();
$sql = "SELECT p.id, p.numero_pedimento, p.patente, p.aduana, p.anio, p.clave_documento,
p.rfc_importador, p.fecha_creacion, p.estado
FROM pedimentos p
WHERE p.id = ? AND p.usuario_id = ?";
$stmt = sqlsrv_query($conn, $sql, [$pedimento_id, $id_usuario]);
if ($stmt === false) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Error de base de datos']);
exit;
}
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
sqlsrv_free_stmt($stmt);
if (!$row) {
echo json_encode(['success' => false, 'message' => 'No encontrado']);
exit;
}
// Formatear fecha si es DateTime
if (isset($row['fecha_creacion']) && $row['fecha_creacion'] instanceof DateTime) {
$row['fecha_creacion'] = $row['fecha_creacion']->format('Y-m-d H:i:s');
}
echo json_encode(['success' => true, 'data' => $row]);
exit;
}
/**
* Devuelve las facturas del pedimento
* GET /IMPORTADORES/catalogo_pedimentos/ajax_facturas?pedimento_id=123
*/
function ajax_facturas()
{
if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'No autorizado']);
exit;
}
$id_usuario = $_SESSION['usuario_id'];
$pedimento_id = isset($_GET['pedimento_id']) ? (int)$_GET['pedimento_id'] : 0;
if ($pedimento_id <= 0) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'ID inválido']);
exit;
}
$conn = getConnection();
// Verificar propiedad
$chk = sqlsrv_query($conn, "SELECT 1 FROM pedimentos WHERE id = ? AND usuario_id = ?", [$pedimento_id, $id_usuario]);
$own = $chk && sqlsrv_fetch_array($chk) ? true : false;
if ($chk) sqlsrv_free_stmt($chk);
if (!$own) {
http_response_code(404);
echo json_encode(['success' => false, 'message' => 'Pedimento no encontrado']);
exit;
}
$sql = "SELECT id, numero_factura, fecha_factura, valor_dolares, valor_factura, cove, moneda, proveedor
FROM pedimento_facturas
WHERE pedimento_id = ?
ORDER BY fecha_factura ASC, id ASC";
$stmt = sqlsrv_query($conn, $sql, [$pedimento_id]);
if ($stmt === false) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Error de base de datos']);
exit;
}
$items = [];
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
if ($r['fecha_factura'] instanceof DateTime) {
$r['fecha_factura'] = $r['fecha_factura']->format('Y-m-d');
}
$items[] = $r;
}
sqlsrv_free_stmt($stmt);
echo json_encode(['success' => true, 'data' => $items]);
exit;
}
/**
* Devuelve las partidas del pedimento
* GET /IMPORTADORES/catalogo_pedimentos/ajax_partidas?pedimento_id=123
*/
function ajax_partidas()
{
if (!($_SESSION['usuario_id'] ?? false)) {
http_response_code(403);
echo json_encode(['success' => false, 'message' => 'No autorizado']);
exit;
}
$id_usuario = $_SESSION['usuario_id'];
$pedimento_id = isset($_GET['pedimento_id']) ? (int)$_GET['pedimento_id'] : 0;
if ($pedimento_id <= 0) {
http_response_code(400);
echo json_encode(['success' => false, 'message' => 'ID inválido']);
exit;
}
$conn = getConnection();
// Verificar propiedad
$chk = sqlsrv_query($conn, "SELECT 1 FROM pedimentos WHERE id = ? AND usuario_id = ?", [$pedimento_id, $id_usuario]);
$own = $chk && sqlsrv_fetch_array($chk) ? true : false;
if ($chk) sqlsrv_free_stmt($chk);
if (!$own) {
http_response_code(404);
echo json_encode(['success' => false, 'message' => 'Pedimento no encontrado']);
exit;
}
$sql = "SELECT id, secuencia, fraccion_arancelaria, descripcion, cantidad, unidad, valor_unitario, peso_neto, peso_bruto
FROM pedimento_partidas
WHERE pedimento_id = ?
ORDER BY secuencia ASC, id ASC";
$stmt = sqlsrv_query($conn, $sql, [$pedimento_id]);
if ($stmt === false) {
http_response_code(500);
echo json_encode(['success' => false, 'message' => 'Error de base de datos']);
exit;
}
$items = [];
while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$items[] = $r;
}
sqlsrv_free_stmt($stmt);
echo json_encode(['success' => true, 'data' => $items]);
exit;
}