558 lines
17 KiB
PHP
558 lines
17 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();
|
|
|
|
// Obtener RFC del importador 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([
|
|
"draw" => intval($_GET['draw'] ?? 0),
|
|
"recordsTotal" => 0,
|
|
"recordsFiltered" => 0,
|
|
"data" => [],
|
|
"error" => "Error al consultar información del importador"
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
$importador = sqlsrv_fetch_array($stmtImportador, SQLSRV_FETCH_ASSOC);
|
|
|
|
if (!$importador) {
|
|
echo json_encode([
|
|
"draw" => intval($_GET['draw'] ?? 0),
|
|
"recordsTotal" => 0,
|
|
"recordsFiltered" => 0,
|
|
"data" => []
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
// 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
|
|
$sqlTotal = "SELECT COUNT(*) AS total FROM PREVIOS_COMPARTIDOS_WS WHERE ClienteRFC = ?";
|
|
$stmt = sqlsrv_query($conn, $sqlTotal, [$importador['rfc']]);
|
|
|
|
if ($stmt === false) {
|
|
echo json_encode([
|
|
"draw" => $draw,
|
|
"recordsTotal" => 0,
|
|
"recordsFiltered" => 0,
|
|
"data" => [],
|
|
"error" => "Error al contar registros totales"
|
|
]);
|
|
exit;
|
|
}
|
|
|
|
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
|
$recordsTotal = (int)($row['total'] ?? 0);
|
|
|
|
// Construir condiciones de filtro
|
|
$where = "ClienteRFC = ?";
|
|
$params = [$importador['rfc']];
|
|
|
|
if ($search !== '') {
|
|
$where .= " AND (Pedimento LIKE ? OR ClienteNombre LIKE ? OR ClavePed LIKE ?)";
|
|
$like = "%{$search}%";
|
|
$params = array_merge($params, [$like, $like, $like]);
|
|
}
|
|
|
|
// Total registros filtrados
|
|
$sqlFiltered = "SELECT COUNT(*) AS total FROM PREVIOS_COMPARTIDOS_WS 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 de la página
|
|
$sqlData = "SELECT IdPrevio, Pedimento, ClienteRFC, ClienteNombre, Timestamp, Status
|
|
FROM PREVIOS_COMPARTIDOS_WS
|
|
WHERE $where
|
|
ORDER BY Timestamp DESC
|
|
OFFSET ? ROWS FETCH NEXT ? ROWS ONLY";
|
|
$params[] = $start;
|
|
$params[] = $length;
|
|
|
|
$stmtD = sqlsrv_query($conn, $sqlData, $params);
|
|
|
|
$data = [];
|
|
if ($stmtD !== false) {
|
|
while ($r = sqlsrv_fetch_array($stmtD, SQLSRV_FETCH_ASSOC)) {
|
|
$timestamp = $r['Timestamp'] instanceof DateTime ? $r['Timestamp']->format('Y-m-d H:i:s') : '';
|
|
$status_text = $r['Status'] == 1 ? 'Activo' : 'Inactivo';
|
|
|
|
$data[] = [
|
|
$r['IdPrevio'],
|
|
$r['Pedimento'],
|
|
$r['ClienteRFC'],
|
|
$r['ClienteNombre'],
|
|
$timestamp,
|
|
$status_text
|
|
];
|
|
}
|
|
}
|
|
|
|
$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;
|
|
} |