UPDATE SOLICITUDES DE IMPO
SE AGREGARON CAMBIOS EN PROVEEDORES Y PARTIDAS EN LA SECCION DE SOLICITUDES DE IMPO
This commit is contained in:
@@ -1,6 +1,70 @@
|
||||
<?php
|
||||
session_start();
|
||||
require_once __DIR__ . '/../../config/database.php';
|
||||
// 1) Composer autoload (phpdotenv y demás libs)
|
||||
require_once __DIR__ . '/../../vendor/autoload.php';
|
||||
|
||||
// 2) Carga nuestro helper de entorno y dispara la carga de .env
|
||||
require_once __DIR__ . '/../helpers/env.php';
|
||||
loadEnv();
|
||||
|
||||
/**
|
||||
* Obtiene (y cachea en sesión) el JWT de la API usando las credenciales de $_ENV
|
||||
*/
|
||||
/**
|
||||
* Obtiene (y cachea) el JWT de la API usando credenciales de $_ENV
|
||||
* Gestiona expiración: asume 1 hora de vida y renueva si ha pasado.
|
||||
*/
|
||||
function getApiToken(): ?string
|
||||
{
|
||||
// Duración en segundos del token (60 min)
|
||||
$ttl = 3600;
|
||||
|
||||
// 1) Si ya tenemos token y no ha expirado, lo devolvemos
|
||||
if (!empty($_SESSION['api_token']) && !empty($_SESSION['api_token_time'])) {
|
||||
$age = time() - $_SESSION['api_token_time'];
|
||||
if ($age < $ttl) {
|
||||
error_log("[getApiToken] Usando token en caché (edad: {$age}s)");
|
||||
return $_SESSION['api_token'];
|
||||
}
|
||||
error_log("[getApiToken] Token expirado (edad: {$age}s), obteniendo uno nuevo");
|
||||
}
|
||||
|
||||
// 2) Sí o sí hacemos login en la API
|
||||
$url = rtrim($_ENV['API_URL'] ?? '', '/') . '/auth/login';
|
||||
$user = $_ENV['API_USER'] ?? '';
|
||||
$pass = $_ENV['API_PASS'] ?? '';
|
||||
$body = json_encode(['username' => $user, 'password' => $pass]);
|
||||
|
||||
error_log("[getApiToken] POST $url → $body");
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
|
||||
CURLOPT_POSTFIELDS => $body,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
$resp = curl_exec($ch);
|
||||
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
error_log("[getApiToken] HTTP $http → $resp");
|
||||
|
||||
if ($http === 200 && ($data = json_decode($resp, true)) && !empty($data['token'])) {
|
||||
// 3) Guardamos token y tiempo actual
|
||||
$_SESSION['api_token'] = $data['token'];
|
||||
$_SESSION['api_token_time'] = time();
|
||||
return $data['token'];
|
||||
}
|
||||
|
||||
// 4) Si no se pudo obtener, devolvemos null
|
||||
error_log('[getApiToken] No se pudo obtener token de la API');
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Listado de solicitudes de importación (facturas) del importador logueado
|
||||
@@ -76,6 +140,13 @@ function crear() {
|
||||
$stmtI = sqlsrv_query($conn, "SELECT INCOTERM,DESCESPANOL FROM dbo.gIncoterms ORDER BY INCOTERM");
|
||||
while ($r = sqlsrv_fetch_array($stmtI, SQLSRV_FETCH_ASSOC)) { $incoterms[] = $r; }
|
||||
|
||||
$unidades_medida = [];
|
||||
$stmtU = sqlsrv_query($conn, "SELECT id, descripcion FROM dbo.unidades_medida_apendice7 ORDER BY id");
|
||||
while ($r = sqlsrv_fetch_array($stmtU, SQLSRV_FETCH_ASSOC)) {
|
||||
$unidades_medida[] = $r;
|
||||
}
|
||||
|
||||
|
||||
include __DIR__ . '/../../views/solicitud_importacion/crear.php';
|
||||
}
|
||||
|
||||
@@ -115,11 +186,7 @@ function guardar() {
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$sql = "INSERT INTO dbo.solicitud_importacion_factura
|
||||
(id_importador,aduana,anexo22_apendice,numero_factura,fecha_factura,
|
||||
numero_pedimento,incoterm,pais_proveedor,tipo_moneda,
|
||||
valor_factura,vinculacion,transportista_id,chofer_id,foto_solicitud_url,status)
|
||||
VALUES(?,?,?,?,?,NULL,?,?,?,?,?,?,?,?,?)";
|
||||
|
||||
$params=[
|
||||
$id_importador,
|
||||
$aduana_seccion,
|
||||
@@ -135,27 +202,71 @@ function guardar() {
|
||||
(int)$chofer_id,
|
||||
$fotoUrl,
|
||||
$status
|
||||
];
|
||||
$stmt=sqlsrv_query($conn,$sql,$params);
|
||||
if($stmt===false) die("Error en guardar():".print_r(sqlsrv_errors(),true));
|
||||
];
|
||||
|
||||
// Obtener nuevo ID
|
||||
$idRow=sqlsrv_query($conn,'SELECT SCOPE_IDENTITY() AS id');
|
||||
$new=sqlsrv_fetch_array($idRow,SQLSRV_FETCH_ASSOC);
|
||||
$id_solicitud=(int)$new['id'];
|
||||
$sql = "INSERT INTO dbo.solicitud_importacion_factura
|
||||
(id_importador, aduana, anexo22_apendice, numero_factura, fecha_factura,
|
||||
numero_pedimento, incoterm, pais_proveedor, tipo_moneda,
|
||||
valor_factura, vinculacion, transportista_id, chofer_id, foto_solicitud_url, status)
|
||||
OUTPUT INSERTED.id_solicitud
|
||||
VALUES (?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
// Partidas
|
||||
if(!empty($_POST['partidas'])&&is_array($_POST['partidas'])){
|
||||
$sqlP="INSERT INTO dbo.solicitud_importacion_partidas
|
||||
(id_solicitud,descripcion,precio_unitario)
|
||||
VALUES(?,?,?)";
|
||||
foreach($_POST['partidas'] as $p){
|
||||
$d=trim($p['descripcion']??'');
|
||||
$u=floatval($p['precio_unitario']??0);
|
||||
if($d!==''&&$u>0) sqlsrv_query($conn,$sqlP,[$id_solicitud,$d,$u]);
|
||||
$stmt = sqlsrv_query($conn, $sql, $params, ['Scrollable' => SQLSRV_CURSOR_KEYSET]);
|
||||
if ($stmt === false) {
|
||||
die("❌ Error ejecutando INSERT con OUTPUT: " . print_r(sqlsrv_errors(), true));
|
||||
}
|
||||
|
||||
$new = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
|
||||
if (!$new || empty($new['id_solicitud'])) {
|
||||
die("❌ No se pudo recuperar el ID insertado de la factura.");
|
||||
}
|
||||
|
||||
$id_solicitud = (int)$new['id_solicitud'];
|
||||
|
||||
|
||||
|
||||
// Partidas
|
||||
if(!empty($_POST['partidas'])&&is_array($_POST['partidas'])){
|
||||
|
||||
$sqlP = "INSERT INTO dbo.solicitud_importacion_partidas
|
||||
(id_solicitud, descripcion, cantidad_comercial, cantidad_tarifa, valor_factura, peso_bruto, unidad_comercial_id, tasa_preferencial)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
$partidas_insertadas = 0; // ← contador
|
||||
|
||||
foreach ($_POST['partidas'] as $i => $p) {
|
||||
error_log("Partida $i: " . print_r($p, true));
|
||||
$params = [
|
||||
$id_solicitud,
|
||||
trim($p['descripcion'] ?? ''),
|
||||
|
||||
floatval($p['cantidad_comercial'] ?? 0),
|
||||
floatval($p['cantidad_tarifa'] ?? 0),
|
||||
floatval($p['valor_factura'] ?? 0),
|
||||
floatval($p['peso_bruto'] ?? 0),
|
||||
intval($p['unidad_comercial_id'] ?? 0) ?: null,
|
||||
|
||||
trim($p['tasa_preferencial'] ?? '')
|
||||
];
|
||||
|
||||
if ($params[1] !== '' && $params[2] > 0) {
|
||||
$stmtPartida = sqlsrv_query($conn, $sqlP, $params);
|
||||
if ($stmtPartida === false) {
|
||||
die("❌ Error insertando partida $i: " . print_r(sqlsrv_errors(), true));
|
||||
} else {
|
||||
$partidas_insertadas++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($partidas_insertadas === 0) {
|
||||
///header('Location: /IMPORTADORES/solicitud_importacion/crear?error_partidas=1');
|
||||
// exit;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
header('Location: /IMPORTADORES/solicitud_importacion/lista?created=ok');
|
||||
exit;
|
||||
}
|
||||
@@ -243,3 +354,110 @@ function eliminar() {
|
||||
header('Location: /IMPORTADORES/solicitud_importacion/lista?deleted=ok'); exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /IMPORTADORES/solicitud_importacion/ajax_proveedores
|
||||
* Devuelve JSON para poblar el select de Proveedor
|
||||
*/
|
||||
function ajax_proveedores()
|
||||
{
|
||||
// 1) Asegura que la respuesta sea JSON
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// 2) Obtén o renueva tu token (usa tu función existente)
|
||||
$token = getApiToken();
|
||||
if (!$token) {
|
||||
echo json_encode(['results' => []]);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) Llama al endpoint de la API de proveedores
|
||||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||||
$url = $apiBase . '/proveedores';
|
||||
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Accept: application/json'],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
$resp = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
// 4) Parsear y transformar al formato { results: [ {id,text}, … ] }
|
||||
$out = ['results' => []];
|
||||
if ($status === 200 && ($json = json_decode($resp, true)) && is_array($json)) {
|
||||
foreach ($json as $p) {
|
||||
$out['results'][] = [
|
||||
'id' => $p['Clave'] ?? '',
|
||||
'text' => $p['Nombre'] ?? ''
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
// 5) Devolver JSON
|
||||
echo json_encode($out);
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function ajax_lista()
|
||||
{
|
||||
// 1) Fijamos el header JSON
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
// 2) Obtener o renovar token
|
||||
$token = getApiToken();
|
||||
if (!$token) {
|
||||
error_log('[ajax_lista] Sin token válido');
|
||||
// Devolvemos estructura vacía
|
||||
echo json_encode(['data' => []]);
|
||||
return;
|
||||
}
|
||||
|
||||
// 3) Construimos la URL de la API
|
||||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||||
$url = $apiBase . '/proveedores';
|
||||
error_log("[ajax_lista] GET $url");
|
||||
|
||||
// 4) Ejecutamos cURL
|
||||
$ch = curl_init($url);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Accept: application/json'],
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 5,
|
||||
]);
|
||||
$resp = curl_exec($ch);
|
||||
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
error_log("[ajax_lista] HTTP $status → $resp");
|
||||
|
||||
// 5) Parseamos y formateamos
|
||||
$dataList = [];
|
||||
if ($status === 200 && ($json = json_decode($resp, true)) && is_array($json)) {
|
||||
foreach ($json as $p) {
|
||||
$clave = htmlspecialchars($p['Clave'] ?? '', ENT_QUOTES);
|
||||
$dataList[] = [
|
||||
$clave,
|
||||
htmlspecialchars($p['Nombre'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['RFC'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['Ciudad'] ?? '', ENT_QUOTES),
|
||||
htmlspecialchars($p['Telefono']?? '', ENT_QUOTES),
|
||||
// Acciones
|
||||
"<a href=\"/IMPORTADORES/proveedores/editar?clave=" . rawurlencode($clave) . "\" class=\"btn btn-sm btn-primary\">✏️</a>
|
||||
<button class=\"btn btn-sm btn-danger\" onclick=\"confirmDelete('{$clave}')\">🗑️</button>"
|
||||
];
|
||||
}
|
||||
} else {
|
||||
error_log('[ajax_lista] Respuesta inválida o status != 200');
|
||||
}
|
||||
|
||||
// 6) Devolvemos siempre HTTP 200 con data (posiblemente vacío)
|
||||
echo json_encode(['data' => $dataList]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user