$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; }