solicitudes impo
This commit is contained in:
@@ -559,7 +559,7 @@ function actualizar() {
|
||||
$vinculacion = $_POST['vinculacion'] ?? 0;
|
||||
$transportista_id = (int)($_POST['transportista_id'] ?? 0);
|
||||
$chofer_id = (int)($_POST['chofer_id'] ?? 0);
|
||||
$status = isset($_POST['status']) ? 1 : 0;
|
||||
$status = isset($_POST['status']) ?? 1;
|
||||
|
||||
// 5) Validar obligatorios
|
||||
if (empty($num_factura) || empty($fecha) || $transportista_id <= 0 || $chofer_id <= 0) {
|
||||
@@ -674,6 +674,136 @@ function eliminar() {
|
||||
header('Location: /IMPORTADORES/solicitud_importacion/lista?deleted=ok'); exit;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
function actualizar_masivo() {
|
||||
header('Content-Type: application/json; charset=utf-8');
|
||||
|
||||
if (!($_SESSION['usuario_id'] ?? false)) {
|
||||
http_response_code(401);
|
||||
echo json_encode(['success' => false, 'error' => 'No autorizado']);
|
||||
exit;
|
||||
}
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Método no permitido']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$ids = $_POST['ids'] ?? [];
|
||||
$status = (int) ($_POST['status'] ?? 0);
|
||||
|
||||
if (empty($ids) || !is_array($ids)) {
|
||||
echo json_encode(['success' => false, 'error' => 'No se recibieron solicitudes']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$conn = getConnection();
|
||||
$usuarioId = $_SESSION['usuario_id'];
|
||||
$token = ($status === 2) ? getApiToken() : null;
|
||||
|
||||
$actualizadas = 0;
|
||||
$fallidas = [];
|
||||
$pedimentosGenerados = [];
|
||||
|
||||
foreach ($ids as $id) {
|
||||
$id = (int)$id;
|
||||
|
||||
// 1. Actualizar el status
|
||||
$sql = "UPDATE dbo.solicitud_importacion_factura SET status = ? WHERE id_solicitud = ? AND id_importador = ?";
|
||||
$stmt = sqlsrv_query($conn, $sql, [$status, $id, $usuarioId]);
|
||||
|
||||
if ($stmt === false) {
|
||||
$fallidas[] = $id;
|
||||
continue;
|
||||
}
|
||||
|
||||
$actualizadas++;
|
||||
|
||||
// 2. Si el status es 2, generar pedimento
|
||||
if ($status === 2 && $token) {
|
||||
$res = generarPedimentoDesdeSolicitud($conn, $id, $usuarioId, $token);
|
||||
if ($res['success']) {
|
||||
$pedimentosGenerados[$id] = $res['numeroPedimento'] ?? null;
|
||||
} else {
|
||||
error_log("[actualizar_masivo] Error en pedimento solicitud $id: {$res['error']}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'actualizadas' => $actualizadas,
|
||||
'fallidas' => $fallidas,
|
||||
'pedimentos' => $pedimentosGenerados
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
function generarPedimentoDesdeSolicitud($conn, $id, $usuarioId, $token) {
|
||||
try {
|
||||
// Consulta solicitud
|
||||
$sqlSel = "SELECT *, '9999' as patente FROM dbo.solicitud_importacion_factura WHERE id_solicitud = ? AND id_importador = ?";
|
||||
$stmtSel = sqlsrv_query($conn, $sqlSel, [$id, $usuarioId]);
|
||||
$solicitud = sqlsrv_fetch_array($stmtSel, SQLSRV_FETCH_ASSOC);
|
||||
if (!$solicitud) return ['success' => false, 'error' => 'Solicitud no encontrada'];
|
||||
|
||||
// Fechas
|
||||
$solicitud['fecha_factura'] = $solicitud['fecha_factura'] instanceof DateTime ? $solicitud['fecha_factura']->format('Y-m-d') : $solicitud['fecha_factura'];
|
||||
$solicitud['created_at'] = $solicitud['created_at'] instanceof DateTime ? $solicitud['created_at']->format('Y-m-d\TH:i:s') : $solicitud['created_at'];
|
||||
$solicitud['updated_at'] = $solicitud['updated_at'] instanceof DateTime ? $solicitud['updated_at']->format('Y-m-d\TH:i:s') : $solicitud['updated_at'];
|
||||
|
||||
// Partidas
|
||||
$partidas = [];
|
||||
$stmtPart = sqlsrv_query($conn, "SELECT * FROM dbo.solicitud_importacion_partidas WHERE id_solicitud = ?", [$id]);
|
||||
while ($p = sqlsrv_fetch_array($stmtPart, SQLSRV_FETCH_ASSOC)) {
|
||||
if ($p['creado_en'] instanceof DateTime) $p['creado_en'] = $p['creado_en']->format('Y-m-d\TH:i:s');
|
||||
$p['cantidad_comercial'] = (float)$p['cantidad_comercial'];
|
||||
$p['cantidad_tarifa'] = (float)$p['cantidad_tarifa'];
|
||||
$p['valor_factura'] = (float)$p['valor_factura'];
|
||||
$p['peso_bruto'] = (float)$p['peso_bruto'];
|
||||
$p['unidad_comercial_id'] = (int)$p['unidad_comercial_id'];
|
||||
$partidas[] = $p;
|
||||
}
|
||||
|
||||
$solicitud['numero_pedimento'] = "";
|
||||
$solicitud['transporte_id'] = null;
|
||||
$solicitud['partidas'] = $partidas;
|
||||
|
||||
$jsonPayload = json_encode($solicitud);
|
||||
$apiBase = rtrim($_ENV['API_URL'] ?? '', '/');
|
||||
$urlPed = $apiBase . '/pedimentos/crearPedimento';
|
||||
|
||||
$ch = curl_init($urlPed);
|
||||
curl_setopt_array($ch, [
|
||||
CURLOPT_CUSTOMREQUEST => 'POST',
|
||||
CURLOPT_HTTPHEADER => ["Authorization: $token", 'Content-Type: application/json'],
|
||||
CURLOPT_POSTFIELDS => $jsonPayload,
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 10,
|
||||
]);
|
||||
$respPed = curl_exec($ch);
|
||||
$httpPed = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
curl_close($ch);
|
||||
|
||||
if ($httpPed === 200 || $httpPed === 201) {
|
||||
$decoded = json_decode($respPed, true);
|
||||
if (isset($decoded['pedimento']['PEDIMENTO'])) {
|
||||
$numeroPed = $decoded['pedimento']['PEDIMENTO'];
|
||||
sqlsrv_query($conn, "UPDATE dbo.solicitud_importacion_factura SET numero_pedimento = ? WHERE id_solicitud = ?", [$numeroPed, $id]);
|
||||
return ['success' => true, 'numeroPedimento' => $numeroPed];
|
||||
}
|
||||
return ['success' => false, 'error' => 'Respuesta inválida de API'];
|
||||
}
|
||||
|
||||
return ['success' => false, 'error' => "HTTP $httpPed"];
|
||||
|
||||
} catch (Exception $e) {
|
||||
return ['success' => false, 'error' => $e->getMessage()];
|
||||
}
|
||||
}
|
||||
/** GET /IMPORTADORES/solicitud_importacion/ajax_proveedores
|
||||
* Devuelve JSON para poblar el select de Proveedor **/
|
||||
function ajax_proveedores()
|
||||
@@ -1120,7 +1250,7 @@ function update_status() {
|
||||
error_log("[update_status] Error al crear pedimento (HTTP $httpPed): $respPed · cURL error: $curlErr");
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'warning' => "Status actualizado, pero fallo al crear pedimento (HTTP $httpPed)"
|
||||
'warning' => "Status actualizado, pero fallo al crear pedimento (HTTP $respPed)"
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user